如何以编程方式按下 QML 按钮?

How to programmatically press QML Button?

我正在用 QML 构建一个对话框。我有一些 TextField,但我希望如果用户按下 enter(发出 accepted 信号),则按下 id: okButton,实际上在视觉上激活了一会儿。

我看到 pressed 属性 是只读的。

谢谢!

你能做到checkable for a short duration while you emulate the click with the checked属性:

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
        }
    }
}

来自 TextFieldaccepted() 信号的文档:

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

您可以简单地调用 clicked() 信号来模拟按钮按下:

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