Search code examples
qtqmlvirtual-keyboard

How to catch Key_Cancel pressed from 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.

enter image description here

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 onKeyCancelPressed and possibly undo the changes made on the textfield before pressing the cancel button.

Thanks.


Solution

  • I think the only way is to respond to it in the Key code itself (textBeforeEditing is your own variable):

    onClicked: InputContext.priv.inputItem.text = InputContext.priv.inputItem.textBeforeEditing
    

    The downside is that this uses private API.