QWebView无法加载外部javascript吗? [英] QWebView not loading external javascript?
问题描述
是否可以使用QWebView从html加载外部javascript文件?
It is possible to load an external javascript file from the html using QWebView?
在以下QtProject中(所有文件位于同一目录中),直接在html内部和外部文件中都有javascript代码.在QWebView中加载它时,我错过了外部行为(在浏览器中可以正常工作):
In the following QtProject (all files in the same directory) there is javascript code directly inside the html and also in an external file. I'm missing the external behavior while loading it in QWebView (in the browser it works fine):
MyApp.pro
MyApp.pro
QT += core gui webkitwidgets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = MyApp
TEMPLATE = app
DESTDIR = ./
SOURCES += main.cpp
HEADERS +=
main.cpp
#include <QApplication>
#include <QtWebKitWidgets>
#include <QFile>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWebView *view = new QWebView;
view->show();
QFile file("qt.html");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return -1;
QString html = QTextStream(&file).readAll();
view->setHtml(html);
return a.exec();
}
qt.html
<html>
<head>
<script type="text/javascript" src="qt.js">
</script>
</head>
<body onload="hello()">
Test..
<script>
alert("Hello World INTERNAL!");
</script>
</body>
</html>
qt.js
function hello() {
alert("Hello World EXTERNAL!");
}
推荐答案
或者1:
似乎未从html评估javascript.换句话说,以下内容无效:
It seems the javascript isn't evaluated from the html. In other words, the following has no effect:
<script type="text/javascript" src="qt.js">
</script>
必须明确地完成:
QString js = readFile("qt.js");
view->page()->mainFrame()->evaluateJavaScript(js);
而且,无需在 setHtml()
中设置 baseUrl
.
或者2:
使用QRC系统并在 setHtml
中设置 baseUrl
.这种方式不需要调用 view-> page()-> mainFrame()-> evaluateJavaScript();
Use the QRC System and set the baseUrl
in setHtml
. This way doesn't require a call to view->page()->mainFrame()->evaluateJavaScript();
// QString js = readFile(":/qt.js");
// view->page()->mainFrame()->evaluateJavaScript(js);
QString html = readFile(":/qt.html");
view->setHtml(html, QUrl("qrc:/"));
application.qrc
application.qrc
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file alias="qt.png">resource/qt.png</file>
<file alias="image.html">resource/image.html</file>
<file alias="qt.html">resource/qt.html</file>
<file alias="qt.js">resource/qt.js</file>
</qresource>
</RCC>
这篇关于QWebView无法加载外部javascript吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!