7

Qt Quick QML MouseArea 事件穿透

 2 years ago
source link: https://www.mycode.net.cn/language/2832.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

MouseArea 是 QML 中一个不可见的鼠标操作区域,可响应所有鼠标事件。一般情况下在自定义按钮、自定义需要鼠标交互的区域时使用。有时你只需要它的 hover 通知来做一些事情,而另外的点击等操作需要传递给其下层的控件,这时你就需要忽略其自身的鼠标按下释放等操作让其消息传递到下层了。

开启事件传递

MouseArea 有一个属性为 propagateComposedEvents,默认为 false,当设置为 true 时,就可以将事件传递给重叠的其他鼠标区域了(包括控件),见 Qt 官方文档:https://doc.qt.io/qt-5/qml-qtquick-mousearea.html#propagateComposedEvents-prop,示例代码如下:

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

以上代码中开启了 propagateComposedEvents 属性,并且将 onClickedmouse.accepted 重置为 false 了,这样 onClicked 事件就会顺利的传递到下层控件中。如果你希望所有点击和释放操作都传递到下层,可以将 onPressed、onReleased 都重写掉,设置 accepted 为 false,如下示例:

MouseArea {
    anchors.fill: parent
    propagateComposedEvents: true
    onClicked: {
        mouse.accepted = false
    }
    onPressed: {
        mouse.accepted = false
    }
    onReleased: {
        mouse.accepted = false
    }
}

这样实现后,这个 MouseArea 的所有点击、按下、释放操作都会传递到下层,而且如果你开启了 hoverEnabled 属性,还不影响 onPositionChanged(鼠标移动)的事件响应,完美的实现了一个鼠标区域只响应鼠标移动但又可以传递点击等事件到下层控件的需求。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK