您不能仅在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"。