QML: pass the mouse event to underlying objects

A QML object's events will be stolen from a MouseArea which covers it. If the underlying object have to receive the events, we can use MouseArea's property: propagateComposedEvents and don't accept the event in the event handlers.

To have a feeling on this property, we have a sample app to check the behaviors.

import QtQuick 2.3

Rectangle {
    visible: true
    width: 800
    height: 480
    color: "pink"
    opacity: 0.5

    MouseArea {
        anchors.fill: parent
        onClicked: {
            console.log("lowest clicked")
        }
    }

    Text {
        text: "lowest level"
        anchors.verticalCenter: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        font.pointSize: 20
    }

    Rectangle {
        width: 400
        height: 300
        color: "skyblue"
        opacity: 0.5

        Text {
            text: "middle level"
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter
            font.pointSize: 20
        }

        MouseArea {
            anchors.fill: parent
            propagateComposedEvents: true
            onClicked: {
                console.log("middle clicked")
                mouse.accepted = false
            }
        }
    }

    Rectangle {
        width: 500
        height: 200
        color: "yellow"
        opacity: 0.5

        Text {
            text: "highest level"
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter
            font.pointSize: 20
        }

        MouseArea {
            anchors.fill: parent
            propagateComposedEvents: true
            onClicked: {
                console.log("highest clicked")
                mouse.accepted = false
            }
        }
    }
}



Above is the screenshot of above codes. Note that setting propagateComposedEvents to true only pass the event to one underlying level. In other words, if we remove the propagateComposedEvents code in middle level's MouseArea, the event won't be passed to the lowest level, but the middle level.


留言

熱門文章