如何使双MouseArea生效?

zzy*_*zzy 2 qt qml qtquick2 qt5.5

这是我的QML代码:

Rectangle
{
    .....
    Rectangle
    {
        ....height and width is smaller than parent
        MouseArea
        {
            id: mouseArea2
            anchors.fill: parent
            hoverEnabled: true

            onEntered:
            {
                console.log("enter 2")
            }
        }
    }


    MouseArea
    {
        id: mouseArea1
        anchors.fill: parent
        hoverEnabled: true

        onEntered:
        {
            console.log("enter 1")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

只有mouseArea1生效.如果我删除mouseArea1然后mouseArea2生效.所以我认为必须处理鼠标事件mouseArea1并让它无法传递给它mouseArea2.

我搜索文档,找出哪个attr可以阻止这种行为,但没有找到.那么如何让它mouseArea1同时mouseArea2生效呢?

MrE*_*Sir 7

对于"组成的"鼠标事件- clicked,doubleClicked并且pressAndHold-您可以在此使用取得propagateComposedEvents属性.但这不适用于此,因为悬停事件不是由事件组成的.

所以你需要做的是改变MouseArea评估s 的顺序.

一个简单的技巧是MouseArea在QML源本身中交换两个s 的顺序.通过将较小的一个放在较大的一个之后,较小的一个优先:

Rectangle{
    //.....
    MouseArea{
        id: mouseArea1
        anchors.fill: parent
        hoverEnabled: true

        onEntered:{
            console.log("enter 1")
        }
    }

    Rectangle{
         //....height and width is smaller than parent
        MouseArea{
            id: mouseArea2
            anchors.fill: parent
            hoverEnabled: true

            onEntered:{
                console.log("enter 2")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

实现相同目标的第二种方法是向z最顶层添加一个MouseArea大于下面的索引.默认情况下,每个元素都有一个z索引0,所以只需添加z: 1较小的元素即可MouseArea:

Rectangle{
    //.....
    Rectangle{
        //....height and width is smaller than parent
        MouseArea{
            z: 1              // <-----------------
            id: mouseArea2
            anchors.fill: parent
            hoverEnabled: true

            onEntered:{
                console.log("enter 2")
            }
        }
    }

    MouseArea{
        id: mouseArea1
        anchors.fill: parent
        hoverEnabled: true

        onEntered:{
            console.log("enter 1")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)