问题描述:在使用qml中的popup组件时,将modal属性设置成true,即模态弹窗,popup窗口之外区域的鼠标点击事件被禁用,但是鼠标移动事件仍然被响应,即被弹窗掩盖的id为ma1的MouseArea的onEntered和onExited事件仍然会触发。
代码示例:
Item{
width: 100
height: 100
MouseArea{
id: ma1
hoverEnabled: true
anchors.fill: parent
onEntered:{
console.log("鼠标移入")
}
onExited:{
console.log("鼠标移出")
}
onClicked:{
if(testPopup.opened){
testPopup.open()
}else{
console.log("自动关闭弹窗")
testPopup.close()
}
}
}
Popup {
id: testPopup
modal: true
contentWidth: 30
contentHeight: 30
contentItem: Rectangle{
anchors.fill: parent.contentItem
MouseArea{
id: ma2
anchors.fill: parent
onClicked:{
console.log("手动关闭弹窗")
testPopup..close()
}
}
}
}
}
解决方案:通过使用Overlay附加类型控制模态弹窗的遮蔽区域(也能设置非模态弹窗的遮蔽区域或者弹窗位置等属性,具体可以去官方文档中查看),本文中用的是模态弹窗,因此使用的是附加类型Overlay的modal属性,具体代码如下:
Item{
width: 100
height: 100
MouseArea{
id: ma1
hoverEnabled: true
anchors.fill: parent
onEntered:{
console.log("鼠标移入")
}
onExited:{
console.log("鼠标移出")
}
onClicked:{
if(testPopup.opened){
testPopup.open()
}else{
console.log("自动关闭弹窗")
testPopup.close()
}
}
}
Popup {
id: testPopup
modal: true
contentWidth: 30
contentHeight: 30
contentItem: Rectangle{
anchors.fill: parent.contentItem
MouseArea{
id: ma2
anchors.fill: parent
onClicked:{
console.log("手动关闭弹窗")
testPopup..close()
}
}
}
Overlay.modal: Rectangle{//设置模态弹窗遮蔽颜色
color: "transparent"
MouseArea{
preventStealing: true
}
}
}
}
上述代码中,modal后的矩形组件用于设置遮蔽颜色及鼠标区域,鼠标区域中的preventStealing属性的作用在文档中直译为 “此属性用于控制该鼠标区域的鼠标事件是否被窃取”,这里设置为true实现了我想要的效果:防止任何鼠标事件被其他鼠标区域获取。