Jeggu
Jeggu

Reputation: 579

Not able to handle child rect mouse events in QML

I have a parent rectangle on top of it there is a child rectangle, both rectangles having mouse events but child rectangle is not taking any mouse event always parent rectangle is handling.

main.qml

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 500
    height: 500
    title: qsTr("Hello World")
    Rectangle{
        id: outerrect
        color: "green"
        anchors.fill: parent
        Rectangle{
            id: innerrect
            width: 100
            height: 100
            color: "lightblue"
            anchors.centerIn: parent
            MouseArea{
                anchors.fill: parent
                hoverEnabled: true
                onClicked: {
                    console.log("child")
                }
            }
        }
        MouseArea{
            anchors.fill: parent
            hoverEnabled: true
            onClicked: {
                console.log("parent")
            }
        }
    }
}

Issue:

Not able to handle child rectangle mouse events

Upvotes: 2

Views: 1230

Answers (1)

Orest Hera
Orest Hera

Reputation: 6776

See the example and explanation for the property propagateComposedEvents of MouseArea QML Type

So, if you want to handle the click only by the child rectangle you can change the order of the MouseArea block in the parent and the child Rectangle block. It changes the order of handling events by blocks.

To activate both handlers the top object should have propagateComposedEvents: true property and also mouse.accepted = false should be set in the onClicked handler, for example:

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

Upvotes: 2

Related Questions