I'm trying to implement a keyboard shortcut control for my qml application. I know there's the possibility to do that with an Action element, but I don't want menus and toolbars which are then mandatory to use.
That's why I'm approaching this topic with keyboard events. For this, I need to have the element performing the action to be in focus. But my goal is a global shortcut control, so theoratically I'd need to have all the elements in question in focus.
I found the FocusScope
type in the documentation, but I'm not sure if this is what I need.
Does it mean that the focus of nested FocusScopes
'slides' through to the last element that's not a FocusScope
and acquiring focus manually with focus: true
thus only this last element holding focus? Or do all the elements on the way down the slide that acquire focus have the activeFocus
property set?
Is this the right approach or would I need something else?
Maybe there are different ways of achieving this, but the way I know is the following one.
The idea is to have an
Item
which controls the key events you need to handle.I'll explain myself with an example. As you will see, if we have input widgets (i.e.
TextInput
) we have to implement a mechanism to return the input to ourItem
in order to process again the keyboard events. In this example, theQt.Key_Escape
key will be used to set the focus back.Edit #1: @Mitch suggested to use the
Shortcut
QML Type. If you can use it (it's available since Qt 5.5), the code will be slightly different. Anyway, you need also to set the focus to the main app in some cases depending on the shortcut sequences implemented. For example, if we're typing text,Shift+Q
doesn't have effect in this example. We need to press Escape first.Much like Mitch, I found focus to be a mess in QML, much like many other aspects of it.
I ended up implementing my own "active focus / selection" scheme. Basically I keep a list of item pointers as my "active selection", I have the keyboard focus fixed at a single item acting as an event dispatcher, and it redirects keyboard events to all items in the active selection list. I still use QML's
MouseArea
to manage the selected items.Focus in Qt Quick is a mess in my opinion. It always confuses me and I end up hacking around it with
forceActiveFocus()
. I'd recommend the newShortcut
type:With the
context
property, you can choose whether you want the shortcut to apply to the current window or the entire application.The motivation for this type can be seen in the comments of patch set 5: