Qt與Js交互
#include <QWebEngineView>
#include <QWebChannel>
#include <QWebEngineScript>
#include <QWebEngineScriptCollection>
void MainWindow::loadJS()
{
QFile webChannelJsFile("./js/qwebchannel.js");
if(!webChannelJsFile.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this, "Warning", "Open qwebchannel.js failed!");
return;
}
else
{
QByteArray webChannelJs = webChannelJsFile.readAll();
QFile jsFile("./js/index.js");
if(!jsFile.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this, "Warning", "Open index.js failed!");
return;
}
else
{
QByteArray tempJs = jsFile.readAll();
webChannelJs.append(tempJs);
script = new QWebEngineScript;
script -> setSourceCode(webChannelJs);
script -> setName("./js/qwebchannel.js");
script -> setWorldId(QWebEngineScript::MainWorld);
script -> setInjectionPoint(QWebEngineScript::DocumentCreation);
script -> setRunsOnSubFrames(false);
}
jsFile.close();
}
webChannelJsFile.close();
channel = new QWebChannel(this);
channel -> registerObject(QStringLiteral("contentObj"), this);
}
void MainWindow::showHtml()
{
webView = new QWebEngineView;
webView -> page() -> scripts().insert(*script);
webView -> page() -> setWebChannel(channel);
webView -> page() -> load(QUrl(QFileInfo("./html/index.html").absoluteFilePath()));
webView -> show();
}
// index.js
window.onload = function()
{
new QWebChannel(qt.webChannelTransport, function(channel)
{
var contentObj = channel.objects.contentObj;
contentObj.sendDevCntToHtml_sig.connect(function(devCnt) // 在qt頭文件中定義的信號:void sendDevCntToHtml_sig(int dev);
{
document.getElementById("devCnt").innerText = devCnt;
})
document.getElementById("ToQtBtn").onclick = function()
{
var str = "string from Js...";
contentObj.getStrFromJs(str); // 在qt頭文件中的定義:Q_INVOKABLE void getStrFromJs(const QString& str);
}
})
}