I'm trying to send a custom QKeyEvent
(like Keypress key B) to an item (like TextField
) in my QML file. This is what I've wrote which it doesn't work. It seems that the item (TextField
) doesn't get my event (I'm assuming this because no B
characters appended to my TextField
's text). I'm capturing click
signal in my ClickHandler
class and then in my handleClick
slot, I try to post an custom event
to my focused item
which in here is a TextField
.
ClickHandler.h
class ClickHandler : public QObject
{
Q_OBJECT
QQmlApplicationEngine* engine;
QApplication* app;
public:
explicit ClickHandler(QQmlApplicationEngine *,QApplication* app);
signals:
public slots:
void handleClick();
};
ClickHandler.cpp:
#include "clickhandler.h"
#include <QMessageBox>
#include <QQuickItem>
ClickHandler::ClickHandler(QQmlApplicationEngine* engine, QApplication* app)
{
this->engine = engine;
this->app = app;
}
void ClickHandler::handleClick()
{
QObject* root = engine->rootObjects()[0];
QQuickItem *item = (root->property("activeFocusItem")).value<QQuickItem *>();
if (item == NULL)
qDebug() << "NO item";
QKeyEvent* event = new QKeyEvent(QKeyEvent::KeyPress,Qt::Key_B,Qt::NoModifier);
QCoreApplication::postEvent(item,event);
}
main.cpp:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QObject* root = engine.rootObjects()[0];
ClickHandler* ch = new ClickHandler(&engine, &app);
QQuickItem* button = root->findChild<QQuickItem*>("button");
QObject::connect(button, SIGNAL(clicked()), ch, SLOT(handleClick()));
return app.exec();
}
main.qml:
ApplicationWindow {
objectName: "rootWindow"
visible: true
Column {
TextField {
id: textId1
objectName: "text1"
text: "text1 message"
focus: true
}
TextField {
id: textId2
objectName: "text2"
text: "text2 message"
}
Button {
objectName: "button"
text : "Click me";
}
}
}