2

这是我的 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")
        }
    }
}

mouseArea1生效。如果我删除mouseArea1mouseArea2生效。所以我认为鼠标事件必须由mouseArea1它处理并且不能传递给mouseArea2.

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

4

2 回答 2

7

对于“组合”鼠标事件 --clickeddoubleClicked--pressAndHold您可以使用该propagateComposedEvents属性实现此目的。但这在这里行不通,因为悬停事件不是组合事件。

因此,您需要做的是更改MouseArea评估 s 的顺序。

一个简单的技巧是交换MouseAreaQML 源本身中两个 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")
            }
        }
    }
}

实现相同目的的第二种方法是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")
        }
    }
}
于 2015-07-28T02:17:59.867 回答
0

我在文档中找到了解决方案。以下面的 QML 代码为例:

import QtQuick 2.0

Rectangle {
    color: "yellow"
    width: 100; height: 100

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

    Rectangle {
        color: "blue"
        width: 50; height: 50

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

这里黄色Rectangle包含一个蓝色矩形。后者是视觉堆叠顺序层次结构中最顶层的项目;它会在视觉上呈现在前者之上。

由于蓝色Rectangle设置propagateComposedEventstrue,并且对于所有接收到的点击事件也设置MouseEvent::acceptedfalse,因此它接收到的任何点击事件都会传播到MouseArea它下方的黄色矩形的 。

单击蓝色Rectangle将导致onClicked其子级的处理程序MouseArea被调用;然后该事件将传播到MouseAreaYellow 的,导致调用Rectangle它自己的处理程序。onClicked

于 2015-07-28T02:16:10.270 回答