Why does QEvent::ShortcutOverride event occur?

White Zebra Source

I have a QMainWindow with an event filter installed. After I open and close a QDialog the keyboard arrow keys don't respond since QMainWindow receives only ShortcutOverride events instead of KeyPress events.

When I changed the QMainWindow's event filter to handle ShortcutOverride events I got a strange behavior since in my program each key press event is preceded by two shortcut override events (why??).

This doesn't work - events are handled more than once:

bool eventFilter(QObject *, QEvent *event) {
  if(type == QEvent::KeyPress || type == QEvent::ShortcutOverride) {
    QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

    switch(keyEvent->key()) {
    case Qt::Key_Up:
    case Qt::Key_Down:
    case Qt::Key_Left:
    case Qt::Key_Right:
      // Do something here
      break;
    default:
      break;
    }

    return true;
  }

  return false;
}

Why is this happening? Where do those ShortcutOverride events come from?

Edit:

As it turns out, QMainwindow loses focus when the QDialog is opened and never gains it back when the QDialog is closed. I used setFocus() in the eventFilter of QMainwindow and it seems to do the trick.

c++qtuser-interfaceevent-handling

Answers

answered 6 years ago Hemant Metalia #1

It is happens when a key press in child is made. It is used to for overriding shortcut key handling (QKeyEvent).

refer http://qt-project.org/doc/qt-4.8/qevent.html#Type-enum

answered 3 years ago mikryz #2

Lost focus is exactly the reason for not getting any keyboard events after a dialog opens up. The solution you suggested is probably the best fix for this issue.

As for ShortcutOverride events, they come for every keypress because any key or combination of keys can be registered as a shortcut. This event gives you an option to cancel shortcut handling, if needed. It has to be processed at the earliest possible moment when the engine doesn't know yet if the pressed key is going to be used as a shortcut or not. Thus the event is generated for all key presses "just in case". You may read more here: https://wiki.qt.io/ShortcutOverride

comments powered by Disqus