qt - 如何让double MouseArea生效?

标签 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")
        }
    }
}

只有mouseArea1 生效。如果我删除 mouseArea1 然后 mouseArea2 生效。所以我认为鼠标事件必须由mouseArea1处理,不能传递给mouseArea2

我搜索文档以找出哪个 attr 可以防止此类行为,但没有找到。那么如何让mouseArea1mouseArea2同时生效呢?

最佳答案

对于“复合”鼠标事件——clickeddoubleClickedpressAndHold——您可以使用 propagateComposedEvents 实现此目的属性(property)。但这在这里行不通,因为悬停事件不是组合事件。

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

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

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")
        }
    }
}

关于qt - 如何让double MouseArea生效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31666001/

相关文章:

c++ - 尝试启动新线程时设置不正确

c++ - QML错误: qrc:/Main. qml:24模块 "system"未安装

gridview - 动态填充 GridView 时应用程序启动缓慢

qt - 如何在委托(delegate)中对齐 QML 组件

android - 将带有 Javascript 数组的对象附加到 QML ListModel 会导致 SEGFAULT

c++ - 功能: Getting clicked object from QGraphicsScene

c++ - 如何声明从 QApplication 派生的 Qt 类并覆盖通知函数?

qt - 如何使用 Homebrew 软件安装Qt4

c++ - 将 Qt 应用程序与 QML 静态链接

javascript - 当 JS 代码在应用程序构建时未知时从 QML 调用 JS 函数(帽子提示 SpiderMonkey)