How can I simulate user interaction (key press event) in Qt?
Asked Answered
R

2

29

I need to simulate Enter key event in Qt. How can I do this?

Richers answered 9/1, 2010 at 23:4 Comment(0)
M
27

The correct answer might be this:

QKeyEvent *event = new QKeyEvent ( QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
QCoreApplication::postEvent (receiver, event);

In fact, there are no matching function for call to:

QtKeyEvent::QtKeyEvent(Type type, int key)

but there is:

QtKeyEvent::QtKeyEvent(Type type, int key, Qt::KeyboardModifiers modifiers)
Makell answered 23/1, 2012 at 15:10 Comment(3)
Should be Qt::NoModifier not Qt::NoModifiers.Nightclub
It's important to simulate a KeyPress followed by a KeyReleased because there are objects that process something when the key is released. An example is a QWebView running a JavaScript that handles keyUp events. They won't be generated unless you post a KeyRelease event.Tien
You can also use shareEvent if you'd rather the QKeyEvent be allocated on the stack.Cornelius
H
23
QKeyEvent *event = new QKeyEvent ( QEvent::KeyPress, Qt::Key_Enter);
QCoreApplication::postEvent (receiver, event)
Hokkaido answered 10/1, 2010 at 0:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.