3
votes

I'm having an issue with my QML program. In the top-level main.qml file, I have some keyboard Shortcuts like so:

Shortcut {
  sequence: "Up"
  onActivated: {
    // yadda yadda
  }
}

In another file, I have several Keys.onPressed calls like this:

Keys.onPressed: {
  if (event.key == Qt.Key_Up) {
    // yadda yadda
  }
}

Apparently, the Shortcuts are interfering with the OnPressed calls. When I comment out the Shortcuts, the OnPressed's work fine. But when they're both active, it seems the Shortcut intercepts the keyboard press and prevents the OnPressed from activating.

I know that with mouse events, Qt has the "accepted" variable. If you want an event to continue propagating down the stack, you can just set "accepted = false" in the OnActivated function in order to accomplish this. However, I am not seeing any equivalent "accepted" variable in the Shortcuts API. Is there some other way I can ensure that the event is propagated correctly?

1

1 Answers

2
votes

In order to act like a shortcut, Shortcut must have a higher priority than key handlers in active focus items. Otherwise it would be no different to a normal key handler. However, sometimes there is a need to override a shortcut, like you do.

In Qt 5.8 and earlier, you can disable a Shortcut to prevent it processing shortcut events under certain conditions. For example:

Shortcut {
    enabled: !someItem.activeFocus
}

In Qt 5.9, a better mechanism has been introduced for this. Active focus items with key handlers can now override shortcuts by accepting shortcut override events using Keys.shortcutOverride. For example:

Item {
    focus: true
    Keys.onShortcutOverride: {
        if (event.key == Qt.Key_Up)
            event.accepted = true
    }
    Keys.onUpPressed: ...
}