• 1000 *
Попробуйте следующее:
файл 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 file:
#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)
}
}
}
}