首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >WebEngineView获取文本输入焦点

WebEngineView获取文本输入焦点
EN

Stack Overflow用户
提问于 2022-05-05 11:54:59
回答 1查看 168关注 0票数 1

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

我需要这些信息来显示/隐藏虚拟键盘。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-06 09:40:14

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

QML侧:

代码语言:javascript
运行
复制
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源:的函数

代码语言:javascript
运行
复制
...
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头部分:

代码语言:javascript
运行
复制
...
Q_INVOKABLE QString qwebchannelSource();
...

SystemManager注意:对象必须是暴露于QML

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72126743

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档