情景:使用html展示页面,并可以与js交互
编译准备
// 1, 编译器需要用MSVC2017 64bit或MSVC2015 32bit,MinGW 32bit是没有下面需要的模块的
// 2, pro文件先添加模块
QT += webenginewidgets webchannel
// 3, 头文件
#include <QWebChannel>
#include <QWebEngineView>
#include <QWebEngineScript>
#include <QWebEngineProfile>
#include <QWebEngineScriptCollection>
#include <QWebChannelAbstractTransport>
#include <QNetworkProxyFactory>
js准备
QFile webChannelJsFile("./js/qwebchannel.js"); // 这是系统的js文件,拷贝放在自己的js目录下
if(!webChannelJsFile.open(QIODevice::ReadOnly))
{
return;
}
else
{
webChannelJs = new QByteArray;
*webChannelJs = webChannelJsFile.readAll();
QFile indexJsFile("./js/index.js"); // 自己与html交互的js文件
if(!indexJsFile.open(QIODevice::ReadOnly))
{
return;
}
else
{
QByteArray tempJs = indexJsFile.readAll();
webChannelJs -> append(tempJs); // 把自己的js追加到qwebchannel.js内容后
script = new QWebEngineScript;
script -> setSourceCode(*webChannelJs);
script -> setName("./js/qwebchannel.js");
script -> setWorldId(QWebEngineScript::MainWorld);
script -> setInjectionPoint(QWebEngineScript::DocumentCreation);
script -> setRunsOnSubFrames(false);
}
indexJsFile.close();
}
webChannelJsFile.close();
给channel注册对象
channel = new QWebChannel(this);
channel -> registerObject(QStringLiteral("contentObj"), this);
html载入js并显示
webView = new QWebEngineView;
webView -> setAttribute(Qt::WA_DeleteOnClose);
webView -> page() -> scripts().insert(*script);
webView -> page() -> setWebChannel(channel);
webView -> page() -> load(QUrl(QFileInfo("./html/index.html").absoluteFilePath()));
webView -> show();
js文件
// index.js
window.onload = function() // 这是第二行,上面需要空一行,不然好像会报错
{
new QWebChannel(qt.webChannelTransport, function(channel)
{
var contentObj = channel.objects.contentObj; // 使用qt注册好的对象
// 接收qt过来的信号
contentObj.sendHelloToHtml_sig.connect(function(str) // 在qt代码合适地方"emit sendHelloToHtml_sig("hello");"即可
{
document.getElementById("txt").innerText = str;
})
// 调用qt的函数
document.getElementById("msg").onclick = function()
{
var msg= "this msg from js!";
contentObj.getMsg(msg);
}
})
}
qt相应代码
emit sendHelloToHtml_sig("hello"); // 发给js接收处理
Q_INVOKABLE void getMsg(const QString& msg);
void Widget::getMsg(const QString& msg)
{
qDebug() << msg;
QMessageBox::information(this, "info", msg);
}
扩展
在QWebEngineView页面下载
// load_html()
QNetworkProxyFactory::setUseSystemConfiguration(false);
webView -> load(QUrl("http://xxx.com"));
QWebEngineProfile* webProfile = webView -> page() -> profile();
connect(webProfile, SIGNAL(downloadRequested(QWebEngineDownloadItem*)), this, SLOT(on_webDownload(QWebEngineDownloadItem*)));
webView -> setWindowModality(Qt::ApplicationModal);
webView -> show();
// on_webDownload(QWebEngineDownloadItem *item)
connect(item, SIGNAL(finished()), this, SLOT(on_downloadFinished()));
connect(item, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(on_downloadProgress(qint64,qint64)));
qDebug() << "item->path(): " << item->path();
item -> setPath(path);
item -> accept();