编辑:这不是重复的。链接的问题处理一个 CORS 安全问题,其中浏览器不允许您从不同来源加载脚本。我的问题与基本资源加载方案(file:///
vsqrc:/
)有关。
我正在尝试使用该file:///
方案在 QWebEngineView 中加载本地 html 文档。html 文件还引用了本地存储的 jquery 库。加载页面的代码如下:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
// center window on desktop
w.setGeometry(QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
w.size(),
a.desktop()->availableGeometry()
));
// Add WebEngineView
QWebEngineView* view = new QWebEngineView;
QWebEngineSettings* settings = view->settings();
settings->setAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls, true);
settings->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls,true);
view->setUrl(QUrl(QStringLiteral("file:///app/ui/main.html")));
// Make it the one and only widget
w.setCentralWidget(view);
w.show();
return a.exec();
}
接下来是简约的 html 文档:
<html>
<head>
<script src="libs/jquery-3.2.1.min.js"/>
</head>
<body>
<h2>Hello World</h2>
<script>
$(function() {
alert('loaded');
});
</script>
</body>
</html>
文档加载正常,但 JavaScript 失败并出现以下错误:
js: Not allowed to load local resource
无论如何,如何强制 QWebEngineView 加载和执行脚本?
编辑:我按照@eyllanesc 的建议进行操作,并将我的所有文件添加为 qrc 资源。现在效果很好。
这是更新后的源代码(注意 C++ 和 HTML 代码中对 qrc 资源的引用):
#include "mainwindow.h"
#include <QApplication>
#include <QWebEngineView>
#include <QStyle>
#include <QDesktopWidget>
#include <QWebEngineSettings>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
// center window on desktop
w.setGeometry(QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
w.size(),
a.desktop()->availableGeometry()
));
// Add WebEngineView
QWebEngineView* view = new QWebEngineView;
QWebEngineSettings* settings = view->settings();
//settings->setAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls, true);
//settings->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls,true);
view->setUrl(QUrl("qrc:/ui/main.html"));
// Make it the one and only widget
w.setCentralWidget(view);
w.show();
return a.exec();
}
以及对应的html文件:
<html>
<head>
<script src="qrc:/ui/libs/jquery-3.2.1.min.js"></script>
</head>
<body>
<h2>Hello World</h2>
<script>
$(function() {
alert( "Document ready!" );
});
</script>
</body>
</html>