torstai 18. huhtikuuta 2013

Registering actions in all stacked MouseAreas

The qml MouseArea has a property called propagateComposedEvents that allows composed mouse actions like clicks to be registered in multiple MouseAreas. The following Qml-file demostrates it's use. The example based on Qt Quick 2 Application template provided by Qt Creator 2.7, and run on Qt 5.0.2.

import QtQuick 2.0

Rectangle {
    width: 360
    height: 360
    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }
    Rectangle {
        color: "blue"
        anchors.fill: parent

        MouseArea {
            id: blueMouseArea
            anchors.fill: parent
            hoverEnabled: true
            onClicked: console.log("Blue Clicked");
            onPositionChanged: console.log("Blue Hovered");
        }
    }
    Rectangle {
        color: "red"
        anchors.top: parent.verticalCenter
        anchors.bottom: parent.bottom
        anchors.left: parent.horizontalCenter
        anchors.right: parent.right

        MouseArea {
            id: redMouseArea
            hoverEnabled: true
            anchors.fill: parent
            // Set propagateComposedEvents to true, and "mouse.accepted" to false
            // if you want composed events to be propagated to other MouseAreas that are below,
            // in this case to blueMouseArea. Composed event consists of more
            // basic events. Eg. a click consists of a pressed and a released event
            propagateComposedEvents: true
            onClicked:
            {
                console.log("Red Clicked")
                // Setting "mouse.accepted" to false has to be also done
                // in order for the event to propagate
                mouse.accepted = false
            }
            // Trying desperately to get hover events to propagate to blueMouseArea.
            // The documentation says that the accepted property of the MouseEvent
            // parameter is ignored in "onPositionChanged"-handler. I'm not sure what
            // that means though...
            onPositionChanged:
            {
                console.log("Red Hovered");
                mouse.accepted = false
            }
        }
    }
}

In this example I also try to unsuccesfully propagate hovering. This may be impossible or then I'm just missing something...