建立一個簡單的按鈕

你可以使用 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";
            }
        }
    }
}