qml 创建一个简单的按钮

示例

您可以使用MouseArea组件轻松地在可单击按钮中转换每个组件。下面的代码显示一个360x360窗口,中间带有一个按钮和一个文本。按下按钮将更改文本:

import QtQuick 2.0

Rectangle {
    width: 360
    height: 360

    Rectangle {
        id: button

        width: 100
        height: 30
        color: "red"
        radius: 5     // 让我们将矩形的角变圆一点,使其更像一个按钮
        anchors.centerIn: parent

        Text {
            id: buttonText
            text: qsTr("Button")
            color: "white"
            anchors.centerIn: parent
        }

        MouseArea {
            //我们将MouseArea设为与其父级(即矩形)一样大。因此,按下按钮上的任意位置都会触发事件
            anchors.fill: parent

            // Exploit the built-in "clicked" signal of the MouseArea component to do something when the MouseArea is clicked.
            //请注意,与信号关联的代码是纯JavaScript。我们可以使用其ID引用任何QML对象
            onClicked: {
               buttonText.text= qsTr("Clicked");
               buttonText.color= "black";
            }
        }
    }
}