Friday, April 23, 2010

Mouse event on QML

How do we hook the call back event like mouse click to the QML applications? The most QML-ish way to do that is to set the element like XXXXArea. This sample shows changing the text colot when mouse buttons (left or right) are clickked with concrete element MouseArea.

At first, see the MouseArea and its parent element:
    Text {
        id: original
        x: 60
        y: 80
        text: qsTr("Hello World")
        MouseArea {
            /* inherit parent item area to handle click event
                because default area is none */
            anchors.fill: parent
            /* write acceptable buttons
                because there are no default button events*/
            acceptedButtons: Qt.LeftButton | Qt.RightButton
            onClicked: { // hooked event when mouse is clicked
                if (mouse.button == Qt.RightButton) {
                    parent.color = 'black';
                } else {
                    parent.color = 'red';
                }
            }
        }
    }

Inside MouseArea element, There are 3 leverage points.
  • anchors.fill: parent means making mouse area enable same as parent item (in this case, it is Text). If you don't set this, enabled mouse areas are nothing yet.
  • acceptedButtons: Qt.LeftButton | Qt.RightButton means making both mouse left button and mouse right button enable. If you don't set this, enabled mouse buttons are nothing yet.
  • onClicked: {} is hooked event when mouse is clicked.
All of this sample QML application is below:
import Qt 4.7

Rectangle {
    width: 200
    height: 200
    Text {
        id: original
        x: 60
        y: 80
        text: qsTr("Hello World")
        MouseArea {
            /* inherit parent item area to handle click event
                because default area is none */
            anchors.fill: parent
            /* write acceptable buttons
                because there are no default button events*/
            acceptedButtons: Qt.LeftButton | Qt.RightButton
            onClicked: { // hooked event when mouse is clicked
                if (mouse.button == Qt.RightButton) {
                    parent.color = 'black';
                } else {
                    parent.color = 'red';
                }
            }
        }
    }
    Text {
        x: original.x
        y: original.y + 16
        text: original.text + "!"
        font {
            family: "Helvetica"
            pointSize: 12
            italic: true
        }
        color: "blue"
        transform: Scale {
            xScale: 1.25
            yScale: 0.8
        }
        transform: Rotation {
            angle: 45
        }
        smooth: true
    }
}

Let's run and click the above text with left button:
Then click it with right button:

No comments:

Post a Comment