我认为 thefocusObject
是实际点击的按钮,所以发送一个QKeyEvent
而不是发送一个TextField
是没有意义的。
如何传递实际接收器对象的指针而不是QGuiApplication
请求focusObject
.
尝试这个:
keyemitter.h 文件(仅标题,不需要 cpp 文件):
#ifndef KEYEMITTER_H
#define KEYEMITTER_H
#include <QObject>
#include <QCoreApplication>
#include <QKeyEvent>
class KeyEmitter : public QObject
{
Q_OBJECT
public:
KeyEmitter(QObject* parent=nullptr) : QObject(parent) {}
Q_INVOKABLE void keyPressed(QObject* tf, Qt::Key k) {
QKeyEvent keyPressEvent = QKeyEvent(QEvent::Type::KeyPress, k, Qt::NoModifier, QKeySequence(k).toString());
QCoreApplication::sendEvent(tf, &keyPressEvent);
}
};
#endif // KEYEMITTER_H
main.cpp 文件:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQmlContext>
#include "keyemitter.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView view;
KeyEmitter keyEmitter;
view.rootContext()->setContextProperty("keyEmitter", &keyEmitter);
view.setSource(QStringLiteral("qrc:/main.qml"));
view.show();
return app.exec();
}
main.qml 文件:
import QtQuick 2.12
import QtQuick.Controls 2.12
Rectangle {
anchors.fill: parent
color: "red"
Column{
Row {
TextField {
id: tf
Component.onCompleted: { console.log(tf); }
text: "123"
}
}
Row {
Button {
text: "1"
onClicked: keyEmitter.keyPressed(tf, Qt.Key_1)
}
Button {
text: "2"
onClicked: keyEmitter.keyPressed(tf, Qt.Key_2)
}
Button {
text: "3"
onClicked: keyEmitter.keyPressed(tf, Qt.Key_3)
}
}
Row {
Button {
text: "DEL"
onClicked: keyEmitter.keyPressed(tf, Qt.Key_Backspace)
}
Button {
text: "OK"
onClicked: keyEmitter.keyPressed(tf, Qt.Key_Enter)
}
Button {
text: "ESC"
onClicked: keyEmitter.keyPressed(tf, Qt.Key_Escape)
}
}
}
}