转载自:http://ldlnew.blog.163.com/blog/static/1060746201242994314216/
一、QT支持Js流程
QT与JavaScript互调是通过QWebFrame的两个函数来实现的:addToJavaScriptWindowObject()将QObject对象传给JS,这样JS就能调用QObject的public slots函数。QT通过evaluateJavaScript()直接调用JS中的函数。流程如下(《QT高级编程》中插图):
![QT与JavaScript互调 - 虹 - 杨柳千丝,绊惹春风](http://img5.ph.126.net/LbD0sTua5j_1P_6g3MHdAA==/2656279355236030315.jpg)
二、示例
使用QWebKit创建一个包含浏览器和工具按钮窗口,在该浏览器中载入包括Js的html,工具按钮调用html中的js
1、工程中引入 webkit
工程文件中增加加:QT += webkit network
2、载入html网页
m_pWebView = new QWebView;
m_pWebView->load(QUrl(tr("G:\\html特效示例\\jsTest.html")));
3、开户js支持
QWebSettings *pWebSettings = m_pWebView->page()->settings();
pWebSettings->setAttribute(QWebSettings::JavascriptEnabled,true);
4、窗体布局
//添加按钮
QPushButton *pEventBtn = new QPushButton(tr("QT Invok Js"));
QPushButton *pcloseBtn = new QPushButton(tr("close"));
//布局:网页与按钮为上下布局,两按钮为水平居中布局
QHBoxLayout *pBtnLayout = new QHBoxLayout;
pBtnLayout->addWidget(pEventBtn);
pBtnLayout->addWidget(pcloseBtn);
pBtnLayout->setAlignment(Qt::AlignCenter);
QVBoxLayout *pMainLayout = new QVBoxLayout;
pMainLayout->addWidget(m_pWebView);
pMainLayout->addLayout(pBtnLayout);
QWidget *widget = new QWidget;
widget->setLayout(pMainLayout);
setCentralWidget(widget);
5、建立信号与槽
//每次载入html时发送段信号
connect(m_pWebView->page()->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()), this,SLOT(addObjectToJs()));
//按钮信号
connect(pEventBtn,SIGNAL(clicked()),this,SLOT(testJs()));
connect(pcloseBtn,SIGNAL(clicked()),this,SLOT(close()));
6、JS调用QT中的public slots
6.1、头文件中申明public slots:
public slots:
void jsInvokQt();
6.2、将QObject<span courier="" new";="" mso-hansi-font-family:"courier="" new";mso-bidi-font-family:"courier="" mso-font-kerning:0pt;mso-ansi-language:x-none;"="" style="line-height: 22px; font-size: 10pt; font-family: 宋体;">与js绑定
void MainWindow::addObjectToJs()
{
m_pWebView->page()->mainFrame()->addToJavaScriptWindowObject("MainWindow",this);
}
6.3、Js中调用QT的 jsInvokQt()函数
function disp_qtmessage()
{
MainWindow.jsInvokQt();
}
7、QT调用JS函数disp_messagebox()
void MainWindow::testJs()
{
m_pWebView->page()->mainFrame()->evaluateJavaScript("disp_messagebox()");
}
三、附含JS的html源码:
<html>
<head>
<script type="text/javascript">
function disp_messagebox()
{
alert("This is javaScript MessageBox!")
}
function disp_qtmessage()
{
MainWindow.jsInvokQt();
MainWindow.setInfor("Qt change string");
alert(MainWindow.getInfor());
}
</script>
</head>
<body>
<input type="button" οnclick="disp_qtmessage()" value="InvokQt" />
</body>
</html>