qml模态弹窗过滤鼠标移动事件

博客介绍了在使用Qt QML的Popup组件时遇到的问题,即设置modal属性为true后,虽然阻止了点击事件,但鼠标移动事件仍然能触发被遮挡的MouseArea。为了解决这个问题,提出了使用Overlay附加类型的modal属性,通过添加一个透明的矩形和设置preventStealing为true来阻止鼠标事件传递,从而实现完全屏蔽鼠标事件的效果。
摘要由CSDN通过智能技术生成

问题描述:在使用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实现了我想要的效果:防止任何鼠标事件被其他鼠标区域获取。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值