Exposing qml Object to Website/Javascript using QW

2019-05-30 17:42发布

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条回答
The star\"
2楼-- · 2019-05-30 17:52

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.

查看更多
登录 后发表回答