本文主要是介绍Qml MouseArea 事件穿透,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
项目场景:
MouseArea 是 QML 中一个不可见的鼠标操作区域,可响应所有鼠标事件。一般情况下在自定义按钮、自定义需要鼠标交互的区域时使用。有时你只需要它的 hover 通知来做一些事情,而另外的点击等操作需要传递给其下层的控件,这时你就需要忽略其自身的鼠标按下释放等操作让其消息传递到下层了
官方示例:
MouseArea propagateComposedEvents属性,默认值为false, 设置为true时,添加一行代码 mouse.accepted = false ,可以传递鼠标事件。鼠标事件即可通过该MouseArea传递到其下层(Mousea之间的关系不一定非要是parent关系),若不加mouse.accepted = false 则设置propagateComposedEvents属性是无效的,
import QtQuick 2.0Rectangle {color: "yellow"width: 100; height: 100MouseArea {anchors.fill: parentonClicked: console.log("clicked yellow")}Rectangle {color: "blue"width: 50; height: 50MouseArea {anchors.fill: parentpropagateComposedEvents: trueonClicked: {console.log("clicked blue")mouse.accepted = false}}}}
事件顺序:
点击蓝色小方框,打印看看结果是什么?注释掉onPressed onReleased? 呢
Rectangle {color: "yellow"width: 100; height: 100MouseArea {anchors.fill: parentonClicked: {console.log("clicked yellow");}onPressed:{console.log("Pressed yellow")}onReleased:{console.log("Released yellow");}}Rectangle {color: "blue"width: 50; height: 50MouseArea {anchors.fill: parentpropagateComposedEvents: trueonClicked: {console.log("clicked blue")mouse.accepted = false}onPressed:{console.log("Pressed blue")mouse.accepted = false;}onReleased:{console.log("Released blue");mouse.accepted = false;}}}
}
正常点击事件顺序 : pressed->released->clicked 其中 clicked是组合事件,但上述代码在blue 消防框框onPressed之后设置了 mouse.accepted = false; 所以之后的其他事件便接受不到了。
这篇关于Qml MouseArea 事件穿透的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!