情景:使用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();