使用QWebChannel将qml对象公开给Website / Javascript

时间:2017-06-30 15:05:04

标签: javascript qt qml

只要html输入字段在显示QWebEngineView内聚焦,我就想在触摸屏上显示自定义输入设备。因此,我试图通过QWebChannel将输入设备对象暴露给客户端Javascipt,然后一旦输入字段被聚焦,就可以调用输入设备的show方法。

但是,目前我收到以下两个错误之一:

  

未捕获的TypeError:无法读取属性'发送'在第60行未定义

     

未捕获的ReferenceError:第2行未定义QWebChannel

此外,我不确定何时使用 navigator.qtWebChannelTransport 而不是 qt.webChannelTransport 作为QWebChannel的参数。

Window.qml

ApplicationWindow {

    WebView {
        id: webView
        anchors.fill: parent

        // Register keyboard as web channel object.
        webChannel.registeredObjects: [myObject]
    }

    MyObject {
        id: myObject
        WebChannel.id: "myWebObject"
    }
}

WebView.qml

WebEngineView {

    // Load web channel and input method handling scripts.
    userScripts: [
        WebEngineScript {
            injectionPoint: WebEngineScript.DocumentCreation
            name: "QWebChannel"
            sourceUrl: "qrc:///qtwebchannel/qwebchannel.js"
        },

        WebEngineScript {
            injectionPoint: WebEngineScript.DocumentReady
            name: "MyObjectInjector"
            sourceUrl: "qrc:/myscript.js"
        }
    ]
}

myscript.js

window.channel = new QWebChannel(navigator.qtWebChannelTransport, function(channel) {
    var inputs = window.document.getElementsByTagName('INPUT');

    var index;
    for(index=0; index < inputs.length; index++) {
        inputs[index].onfocus = function() {
            console.log("Input focused");
        };
    }
});

1 个答案:

答案 0 :(得分:1)

  

未捕获的ReferenceError:第2行未定义QWebChannel

我猜QWebChannel没有暴露给myscript.js。在WebEngineScript中尝试worldId: WebEngineScript.MainWorld

    WebEngineScript {
        injectionPoint: WebEngineScript.DocumentCreation
        worldId: WebEngineScript.MainWorld
        name: "QWebChannel"
        sourceUrl: "qrc:///qtwebchannel/qwebchannel.js"
    },
  

此外,我不确定何时使用navigator.qtWebChannelTransport而不是qt.webChannelTransport作为QWebChannel的参数。

qt.webChannelTransport似乎是正确的。请参阅https://bugreports.qt.io/browse/QTBUG-52090