3
votes

I want to use a press-and-hold behaviour to switch states of a gui Item.

I use a FocusScope(below) to recieve keyboard events.

FocusScope{
    id:pageFocus

    property var pedalKey//a key id

    Keys.enabled: true
    Keys.onPressed: {
        if(event.key===pedalKey && !event.isAutoRepeat)
        {
            state="a"
        }
    }
    Keys.onReleased: {
        if(event.key===pedalKey && !event.isAutoRepeat)
        {
            state="b"
        }
    }
}

It works, but when FocusScope loses the focus.
The most terrible thing is that I don't know which Item got the focus.
Is there any way to enable the Item to receive keyboard events without focus?

2

2 Answers

3
votes

You can forward key events to other objects (even multiple objects). Here is the example from Qt's documentation:

Item {
    ListView {
        id: list1
        // ...
    }
    ListView {
        id: list2
        // ...
    }
    Keys.forwardTo: [list1, list2]
    focus: true
}
2
votes

It works, but when FocusScope lost the focus.

Yes, key events are only delivered to the items with activeFocus. The event will be sent to the inner-most item first, proceeding up the chain of parents until one of them accepts the events (using e.g. the handlers you're using here).

The most terrible thing is that I don't know which Item got the focus.

You can use the Window.activeFocusItem attached property to see where the focus is currently.

Is there any way to enable the Item to receive keyboard events without focus?

Not easily or directly. You could use event filtering to intercept events before they get to the window, but I would consider that absolutely an option of last resort. Shortcuts are another possibility, depending on what presses you are trying to intercept.