本文主要是介绍Qml学习——鼠标事件处理MouseArea,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近在学习Qml,但对Qml的各种用法都不太熟悉,总是会搞忘,所以写几篇文章对学习过程中的遇到的东西做一个记录。
学习参考视频:https://www.bilibili.com/video/BV1Ay4y1W7xd?p=1&vd_source=0b527ff208c63f0b1150450fd7023fd8
其他文章:
Qml学习——动态加载控件
Qml学习——控件状态
Qml学习——使用JavaScript
Qml学习——动画
Qml学习——鼠标事件处理MouseArea
Qml学习——布局
Qml学习——基本控件
目录
- 1 MouseArea
- 1.1 拖动控件
- 1.2 鼠标事件过滤问题
1 MouseArea
MouseArea是一个处理鼠标事件的项目,它和可见项目是结合使用的。
如以下例程。
import QtQuick 2.12
import QtQuick.Window 2.12Window {visible: true; width: 200; height: 120Rectangle {width: 30; height: 30; color: 'red'MouseArea {anchors.fill: parentonClicked: console.log('red rect')}}Rectangle {width: 30; height: 30; color: 'yellow'anchors.right: parent.rightMouseArea {anchors.fill: parentonClicked: console.log('yellow rect')}}
}
可以捕捉并处理范围内的鼠标事件。
1.1 拖动控件
import QtQuick 2.12
import QtQuick.Window 2.12Window {visible: true; width: 200; height: 120Text {text: 'text'MouseArea {anchors.fill: parentdrag.target: parent}}
}
1.2 鼠标事件过滤问题
import QtQuick 2.12
import QtQuick.Window 2.12Window {visible: true; width: 200; height: 120Rectangle {anchors.fill: parentMouseArea {anchors.fill: parentonClicked: console.log('rectangle')}Text {anchors.centerIn: parenttext: "text"MouseArea {anchors.fill: parentonClicked: console.log('text')}}}
}
点击Text时,事件只被触发了一次,原因是Text处理事件时,默认把事件过滤掉了,导致Rectangle无法接收事件,想要让事件不被过滤,可以把代码改成如下所示。
import QtQuick 2.12
import QtQuick.Window 2.12Window {visible: true; width: 200; height: 120Rectangle {anchors.fill: parentMouseArea {anchors.fill: parentonClicked: console.log('rectangle')}Text {anchors.centerIn: parenttext: "text"MouseArea {anchors.fill: parentpropagateComposedEvents: trueonClicked: {console.log('text')mouse.accepted = false;}}}}
}
这篇关于Qml学习——鼠标事件处理MouseArea的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!