Tuesday, September 3, 2013

qml example: handle events for button

qml example: handle events for button
qml example: handle events for button

To handle events on button, simple handle onClicked:, onPressed:, onReleased:... inside MouseArea.
import QtQuick 2.0

Rectangle {
    width: 360
    height: 360

    Rectangle {
        id: myButton

        width: 200
        height: 120
        anchors.centerIn: parent

        property color buttonColor: "white"
        property color buttonColorPressed: "gray"
        property color buttonBorderColor: "gray"
        property color buttonBorderColorPressed: "black"

        MouseArea{
            id: myButtonMouseArea
            anchors.fill: parent

            onClicked: console.log("Button Clicked")
            onPressed: console.log("Button Pressed")
            onReleased: console.log("Button Released")
        }

        color: myButtonMouseArea.pressed
               ? buttonColorPressed : buttonColor

        border.width: 2
        border.color: myButtonMouseArea.pressed
                      ? buttonBorderColorPressed : buttonBorderColor

        Text{
            id: buttonLabel
            anchors {
                horizontalCenter: parent.horizontalCenter
                top: parent.top
            }
            color: "black"
            text: "Button Label"
        }

        Image {
            id: buttonImage
            source: "http://goo.gl/kdbgF8"
            anchors {
                horizontalCenter: parent.horizontalCenter
                top: buttonLabel.bottom
            }
        }
    }
}

In this example, the MouseArea will emit a clicked signal when the user clicks within the mouse area, and then the onClicked signal handler, declared within the MouseArea, will be invoked.

qml button step-by-step