Exposing qml Object to Website/Javascript using QWebChannel

夙愿已清 提交于 2019-12-23 03:01:15

问题


I would like to display a custom input device on a touchscreen as soon as a html input field gets focused within the displaying QWebEngineView. Therefore I tried to expose the input device object via QWebChannel to the client side Javascipt, which could then invoke the show method of the input device as soon as an input field gets focused.

However, currently I get one of the following two errors:

Uncaught TypeError: Cannot read property 'send' of undefined at line 60

Uncaught ReferenceError: QWebChannel is not defined at line 2

Furthermore I am not sure when to use navigator.qtWebChannelTransport instead of qt.webChannelTransport as parameter for 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:


Uncaught ReferenceError: QWebChannel is not defined at line 2

I guess QWebChannel is not exposed to myscript.js. Try worldId: WebEngineScript.MainWorld in WebEngineScript.

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

Furthermore I am not sure when to use navigator.qtWebChannelTransport instead of qt.webChannelTransport as parameter for QWebChannel.

qt.webChannelTransport seems to be correct. See https://bugreports.qt.io/browse/QTBUG-52090.



来源:https://stackoverflow.com/questions/44849541/exposing-qml-object-to-website-javascript-using-qwebchannel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!