Qml StateMachine KeyEventTransitions

42 Views Asked by At

QtWidgets has the QKeyEventTransition. Looks like theres no equivalent type in QML. How can I transit states based on a key event?

1

There are 1 best solutions below

0
On

A workaround could be to create custom signals that will be manually emitted on certain key presses and used in SignalTransition. I haven't tested to directly connect to escapePressed as Keys is an attached property and needs to be attached to an object that has focus.

import QtQuick
import QtQml.StateMachine as DSM

Window {
    id: root
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    signal escapePressed

    Item {
        id: button
        focus: true
        anchors.fill: parent

        Keys.onPressed: function(event) {
            if (event.key === Qt.Key_Escape) {
                console.log("Escape pressed")
                root.escapePressed()
            }
        }

        DSM.StateMachine {
            id: stateMachine
            initialState: state
            running: true

            DSM.State {
                id: state

                DSM.SignalTransition {
                    targetState: finalState
                    signal: root.escapePressed
                }
            }

            DSM.FinalState { id: finalState }

            onFinished: Qt.quit()
        }
    }
}