7
votes

I am building a dialog in QML. I have some TextField, but I'd like that if the user presses enter (accepted signal is emitted), the id: okButton is pressed, actually activating it visually for a moment.

I see that the pressed property is read only.

Thanks!

2

2 Answers

12
votes

You can simply call clicked() signal for simulating button press:

Keys.onReturnPressed: {
    clicked()
    event.accepted = true
}
3
votes

You can make it checkable for a short duration while you emulate the click with the checked property:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2

ApplicationWindow {
    title: qsTr("Hello World")
    width: 640
    height: 480
    visible: true

    Timer {
        id: timer
        running: true
        repeat: true
        interval: 100
        onTriggered: {
            button.checked = false;
            button.checkable = false;
        }
    }

    Row {
        TextField {
            anchors.verticalCenter: parent.verticalCenter

            onAccepted: {
                button.checkable = true;
                button.checked = true;
                timer.start();
            }
        }

        Button {
            id: button
            text: "Submit"
            anchors.verticalCenter: parent.verticalCenter
        }
    }
}

From the documentation for the accepted() signal of TextField:

This signal is emitted when the Return or Enter key is pressed.