怎么在qt中 加载js脚本,谢谢

JavaScript08

怎么在qt中 加载js脚本,谢谢,第1张

使用Webkit library (可以说是纯QT实现)

代码量不多,直接贴代码 (读起来一点不痛苦的) :

myWebView = new QWebView(this)//this 是main window widget, myWebView 是它的成员变量

myWebView->page()->settings()->setAttribute(QWebSettings::JavascriptEnabled, true)

myWebView->page()->settings()->setAttribute(QWebSettings::PluginsEnabled,true)

myWebView->page()->mainFrame()->addToJavaScriptWindowObject("mainWindowObject", this)//html页面中,可以通过"mainWindowObject"这个对象名访问主控件中的方法 (slot)

setCentralWidget(myWebView)

myWebView->setUrl( xxx )//xxx是你的url或本地html路径

//. . .

class MainWindow : public QMainWindow

{

//. . .

public slots:

void CPlusPlusFunction(const QString&str) //这个函数是将被JavaScript调用的

{

myWebView->page()->mainFrame()->uateJavaScript( QObject::tr("jsFunction('Popup Dialog')") )

}

}

HTML文件内容如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<title>myjstest</title>

<script language="JavaScript" type="text/javascript">

function jsFunction(values) //this function will be called from C++ codes

{

alert(values)

}

function test()

{

mainWindowObject.CPlusPlusFunction( "calling C++ function from javaScript" )

}

</script>

</head>

<body>

<div id="dest"></div><form action="" method="post">

<input type="button" name="" value="myTest" onclick="test()" />

</form>

</body>

</html>

这种方法,使用Webkit作为浏览器,如果你的页面使用了ActiveX控件(比如google earth插件),则不能正常工作。

这种情况下,你需要放弃Webkit,在主程序中调用IE 控件(WebBrowser Control)作为浏览器。(但是这样也失去了跨平台的支持,因为IE只能在Wndosw上跑。)