How is it possible to catch when Key_Cancel pressed from a custom virtual keyboard in qml?



  • I have the following TextField as the inputfield which is linked to a virtual keyboard.

    TextField {
            id: inputField
            color: buttonActive ? Style.buttonColorTextOn : Style.buttonColorTextOff
            text: "100"
            topPadding: 8
            anchors.left: parent.left
            anchors.leftMargin: 8
            anchors.right: icon.left
            anchors.rightMargin: 8
            anchors.top: parent.top
            anchors.topMargin: 6
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 6
            inputMethodHints: Qt.ImhDigitsOnly
            validator: IntValidator { bottom:lowestInput; top: highestInput}
            selectionColor: Style.textSelectionBg
            selectedTextColor: Style.fontcolor1
            font.family: stdFont.name
            horizontalAlignment: TextField.AlignRight
            verticalAlignment: TextField.AlignVCenter
            font.pixelSize: Style.highlightedFontSize
            leftPadding: 3
            rightPadding: 3
            TextMetrics{
                id: textMetrics
                text: inputField.text
                font.family: stdFont.name
                font.pixelSize: Style.highlightedFontSize
            }
    
            background: Rectangle
            {
                color: buttonActive ? Style.buttonColorOn : Style.buttonColorOff
                border.color: buttonActive ? Style.buttonColorTextOn : Style.buttonColorTextOff
                border.width: 1
                Rectangle
                {
                    id: inputFieldColor
                    color: buttonActive ? Style.buttonColorOn : Style.buttonColorOff
                    anchors.top: parent.top
                    anchors.topMargin: inputField.topPadding - 1
                    anchors.right: parent.right
                    anchors.rightMargin: inputField.rightPadding - 1
                    width: textMetrics.width + inputField.rightPadding
                    height: textMetrics.height
                }
            }
        }
    

    This keyboard looks as the following.

    0_1560793756878_4501893d-eb9b-4474-9329-939714bd965d-grafik.png

    Here the cancel key is constructed as the following in the custom layout for the keyboard.

    Key {
                    key: Qt.Key_Cancel
                    text: "cancel"
    }
    

    My question is, how can I catch when the cancel button is pressed on the virtual keyboard? I'd like catch in a slot something like onKeyCancelPressed and possibly undo the changes made on the textfield before pressing the cancel button.

    Thanks.


  • Moderators

    @red.green
    https://doc.qt.io/qt-5/qml-qtquick-keys.html#cancelPressed-signal

    TextField {
       ...
       Keys.onCancelPressed: { ... }
    }
    


  • @raven-worx

    Thanks. I'm really new to QML, so didn't know about the Keys option.