qml Getting started with qml Creating a simple button


Example

You can easily transform every component in a clickable button using the MouseArea component. The code below displays a 360x360 window with a button and a text in the center; pressing the button will change the text:

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