创建一个简单的按钮

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

import QtQuick 2.0

Rectangle {
    width: 360
    height: 360

    Rectangle {
        id: button

        width: 100
        height: 30
        color: "red"
        radius: 5     // Let's round the rectangle's corner a bit, so it resembles more a button
        anchors.centerIn: parent

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

        MouseArea {
            // We make the MouseArea as big as its parent, i.e. the rectangle. So pressing anywhere on the button will trigger the event
            anchors.fill: parent

            // Exploit the built-in "clicked" signal of the MouseArea component to do something when the MouseArea is clicked.
            // Note that the code associated to the signal is plain JavaScript. We can reference any QML objects by using their IDs
            onClicked: {
                buttonText.text = qsTr("Clicked");
                buttonText.color = "black";
            }
        }
    }
}