Binding the color to a click


When a user clicks the button the appearance shall change. We used states in an earlier post about the toggle button. Here we try another approach.

In my first attempt changing the color when a user clicks I hooked up to the onPressed and onReleased handlers from the MouseRegion. See below:

import Qt 4.6

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

We need to define the initial color and then handle the press and release events. I guess this is traditional thinking when someone is used to “=”.

Later I found an example, which inverted the logic. Look here:

import Qt 4.6

Rectangle {
    id: button
    color: if(region.pressed) { "green" } else { "red" }
    // color: region.pressed ? "green" : "red"  // a more compact form
    width: 96; height: 24; anchors.centerIn: parent
    MouseRegion {
      id: region
        anchors.fill: parent;
        onClicked: console.log("clicked()")
    }
}

The color attribute is bound to an expression. This binding “:” is re-evaluated when the expression changes. This is the core idea behind binding. So when region.pressed changes, the expression is evaluated and the result assigned to the color. Really cool!

See Property-Binding from the documentation for more information about binding.

One thought on “Binding the color to a click”

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