简体   繁体   中英

How to programmatically press QML Button?

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!

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM