29

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

NG_
  • 6,895
  • 7
  • 45
  • 67
Andersson83
  • 441
  • 1
  • 8
  • 12

2 Answers2

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)

phyatt
  • 18,472
  • 5
  • 61
  • 80
dnlcrl
  • 5,022
  • 3
  • 32
  • 40
  • 3
    Should be Qt::NoModifier not Qt::NoModifiers. – Therefore May 04 '13 at 20:56
  • 2
    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. – Fappaz Sep 16 '14 at 21:57
  • You can also use `shareEvent` if you'd rather the `QKeyEvent` be allocated on the stack. – Kyle Strand Aug 26 '16 at 01:15
23
QKeyEvent *event = new QKeyEvent ( QEvent::KeyPress, Qt::Key_Enter);
QCoreApplication::postEvent (receiver, event)
PiedPiper
  • 5,735
  • 1
  • 30
  • 40