如何检测使用QML WebEngineView显示的网页上文本字段(输入)的焦点?
我需要这些信息来显示/隐藏虚拟键盘。
发布于 2022-05-06 09:40:14
要获得通过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注意:对象必须是暴露于QML。
https://stackoverflow.com/questions/72126743
复制相似问题