Reputation: 1949
I am trying to send a KeyPress Event to my window application:
QtQuick2ApplicationViewer viewer;
When I press the button in GUI to send the tab KeyPress event to viewer I get the error:
Tab Enter
QCoreApplication::removePostedEvent: Event of type 6 deleted while posted to QtQuick2ApplicationViewer
We can see that SimKeyEvent::pressTab() is triggered, because "Tab Enter" is printed in debug window.
Why do my event get deleted from event queue?
SimKeyEvent.h:
class SimKeyEvent : public QObject
{
Q_OBJECT
public:
explicit SimKeyEvent(QObject *parent = 0, QtQuick2ApplicationViewer *viewer = 0);
private:
QtQuick2ApplicationViewer *viewer;
signals:
public slots:
void pressTab();
};
SimKeyEvent.cpp:
SimKeyEvent::SimKeyEvent(QObject *parent, QtQuick2ApplicationViewer *viewer) :
QObject(parent)
{
this->viewer = viewer;
}
void SimKeyEvent::pressTab()
{
qDebug() << "Tab Enter"; //To confirm that this slot gets called.
QKeyEvent event = QKeyEvent(QKeyEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);
QCoreApplication::postEvent(viewer, &event);
}
main.cpp:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/GC/MainMenu.qml"));
SimKeyEvent *simKeyEvent = new SimKeyEvent(0, &viewer);
QObject *object = viewer.rootObject();
QObject::connect(object, SIGNAL(pressTab()), simKeyEvent, SLOT(pressTab()));
viewer.showMaximized();
return app.exec();
}
Upvotes: 0
Views: 1183
Reputation: 12931
Your QKeyEvent event
object will be destroyed when it goes out of scope (in your case when the function ends).
The docs state this: Adds the event event, with the object receiver as the receiver of the event, to an event queue and returns immediately.
and: The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted. It is not safe to access the event after it has been posted.
So you should create your QKeyEvent
object with new
:
QKeyEvent *event = new QKeyEvent(QKeyEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);
Upvotes: 3