Qt与Js交互

Qt与Js交互

qmake: QT += network webenginewidgets webchannel
#include 
#include 
#include 
#include 

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);
	}
    })
}

你可能感兴趣的:(Qt与Js交互)