Simple useless Button


This is a rather simple and almost useless Button. Essentially we can see a button as a click-able rectangle.

To make the rectangle react on a click, we use the MouseRegion element. It is filled across the parent rectangle and when the user clicks this region a message “clicked()” is printed to the console.

import Qt 4.6

Rectangle {
    width: 200; height: 200

    Rectangle {
        id: button
        color: "red"
        width: 96; height: 24; anchors.centerIn: parent
        MouseRegion {
            anchors.fill: parent;
            onClicked: console.log("clicked()")
        }
    }
}

The lovely user interface looks like this:

When you press the red-rectangle a click message appears.

To make it more useful we would like that the button emits a signal when clicked. For this we extend our previous example and add a signal declaration to our button. The signal is emitted, when the region is clicked.

import Qt 4.6

Rectangle {
    width: 200; height: 200
    Rectangle {
        id: button
        signal clicked
        color: "red"
        width: 96; height: 24; anchors.centerIn: parent
        MouseRegion {
            anchors.fill: parent;
            onClicked: parent.clicked()
        }
    }
    Connection {
        sender: button
        signal: "clicked()"
        script: console.log("clicked()")
    }
}

At the end we connect a signal handler (Connection) to the “clicked()” signal and print on the console “clicked()”.

Now you you could add a Text element centered in the button and also beautify it. It would look already much better and even be useful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s