WebEngineView 获取文本输入焦点

WebEngineView getting text input focus

如何检测使用 QML WebEngineView 显示的网页上文本字段(输入)的焦点?

我需要这些信息来 display/hide 虚拟键盘。

要在通过 QML WebEngineView 显示的网页上获得文本输入焦点,需要使用 WebChannel 和 运行 一些 js 代码在您的网页上。您无需修改​​页面源。

QML 端:

import QtWebEngine 1.5
import QtWebChannel 1.0
...
QtObject{
    id: someObject
    WebChannel.id: "backend"

    function showKeyboard() {
        console.log("Show the keyboard");
        inputEngine.showLiteralKeyboard = true
    }
    function hideKeyboard() {
        console.log("Hide the keyboard");
        inputEngine.hide()
    }
}

WebEngineView{
    id: webview
    url: "https://your-webpage.com/"
    anchors.fill: parent
    settings.javascriptEnabled: true
    webChannel: channel

    onLoadingChanged: {
        if(loadRequest.status === WebEngineView.LoadSucceededStatus){
            webview.runJavaScript(systemManager.qwebchannelSource())
            webview.runJavaScript("
                new QWebChannel(qt.webChannelTransport, function(channel){
                    var backend = channel.objects.backend;
                    var inputs = document.getElementsByTagName('input');
                    var index;

                    for(index=0; index < inputs.length; index++)
                    {
                        inputs[index].onfocus = function(){
                            backend.showKeyboard()
                        };
                        inputs[index].onblur = function(){
                            backend.hideKeyboard()
                        }
                    }
                })")
        }
    }
}

WebChannel{
    id: channel
    registeredObjects: [someObject]
}
...

systemmanager.cpp:包含加载和公开的函数 qwebchannel.js 来源:

...
QString SystemManager::qwebchannelSource()
{
    QFile qwebchannelFile(":/qtwebchannel/qwebchannel.js");     // Load the JS API from the resources
    if(!qwebchannelFile.open(QIODevice::ReadOnly)){
        qDebug()<<"Couldn't load Qt's QWebChannel API!";
    }

    QString scriptSource = QString::fromLatin1(qwebchannelFile.readAll());
    qwebchannelFile.close();

    return scriptSource;
}
...

systemManager.h 具有暴露功能的表头部分:

...
Q_INVOKABLE QString qwebchannelSource();
...

注意: SystemManager 对象必须是 exposed to QML.