将按键事件发送到Qt QML WebEngineView

3
2个回答

2

您不能仅在QML方面完成它,但您可以编写自己的QObject并将其注册为上下文属性。

KeyEventSender类

#include <QObject>
#include <QGuiApplication>
#include <QQuickItem>
#include <QQuickWindow>

class KeyEventSender : public QObject
{
    Q_OBJECT
public:
    explicit KeyEventSender(QObject *parent = nullptr) : QObject(parent) {}
    Q_INVOKABLE void simulateKey(int key, Qt::KeyboardModifiers modifiers, const QString &text) {
        QQuickItem *r = qobject_cast<QQuickItem *>(QGuiApplication::focusObject());
        if (r) {
            bool autorep = false;
            QKeyEvent press = QKeyEvent(QKeyEvent::KeyPress, key, modifiers, text, autorep);
            r->window()->sendEvent(r, &press);
            QKeyEvent release = QKeyEvent(QKeyEvent::KeyRelease, key, modifiers, text, autorep);
            r->window()->sendEvent(r, &release);
        }
    }
};

在main()函数中注册它

#include "keyeventsender.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    KeyEventSender k;
    engine.rootContext()->setContextProperty("keyEventSender",&k);

在QML中使用:

    TextField {
        id: text
        anchors.centerIn: parent
        focus: true
    }

    Timer {
        interval: 2000; running: true; repeat: true
        property bool capital: false
        onTriggered: {
            if (!capital)
                keyEventSender.simulateKey(Qt.Key_K, Qt.NoModifier,"k")
            else
                keyEventSender.simulateKey(Qt.Key_K, Qt.ShiftModifier,"K")

            capital = !capital
        }
    }

注意焦点项目获取键盘事件。当计时器触发时,TextField 将会更新成"kKkKkK"。


1
谢谢回复。我已经成功让像TextField这样的元素上的键盘事件起作用,但是在WebEngineView上却不行。WebEngineView处理按键的方式有所不同。 - James

2
观察到 QTBUG-46251QTBUG-43602,WebEngineView 对于滚动内容进行了自己的键盘处理。
它们建议使用 Action 来解决。
ApplicationWindow {
    width: 1280
    height: 720
    visible: true
    WebEngineView {
        id: webview
        url: "http://www.qt-project.org"
        anchors.fill: parent
        focus: true;
    }

    Action {
        shortcut: "Escape"
        onTriggered: {
            console.log("Escape pressed.");
            Qt.quit();
        }
    }
}

嗨@Mohammad,Actions是我想要在WebEngineView上监听或劫持/吃掉键事件。我想做相反的事情:向WebEngineView注入键事件。 - James

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接