QML反转MouseArea

QML反转MouseArea

  • 最近在项目中遇到一个需求,点击一个按钮显示一个自定义的tips,点击UI其他的地方需要让tips隐藏,正常的思维是通过FocusScope建立起focus系统,当tips focus消失的时候隐藏,这样实现起来会比较耗时;正确的姿势应该是反转MouseArea,当鼠标点击Control以外的部分时,触发clicked信号

InverseArea实现

import QtQuick 2.0

Item {
    id : component

    property Item sensingArea : null

    signal outbound
    signal inbound

    property var _mouseArea : null

    function _setupMouseArea() {
        if (!_mouseArea) {
            _mouseArea = mouseAreaBuilder.createObject(component);
        }
        var p = sensingArea;
        if (!p)
            p = _topMostItem();
        _mouseArea.parent = p;
    }

    function _destroyMouseArea() {
        if (_mouseArea) {
            _mouseArea.destroy();
            _mouseArea = null;
        }
    }

    function _inBound(pt) {
        var ret = false;
        if (pt.x >= component.x &&
            pt.y >= component.y &&
            pt.x <= component.x + component.width &&
            pt.y <= component.y + component.height) {
            ret = true;
        }
        return ret;
    }

    function _topMostItem() {
        var p = component;

        while (p.parent) {
            p = p.parent;
        }
        return p;
    }

    Component {
        id : mouseAreaBuilder
        MouseArea {
            propagateComposedEvents : true
            anchors.fill: parent
            z: 10000
            onPressed: {
                mouse.accepted = false;
                var pt = mapToItem(component.parent,mouse.x,mouse.y)
                if (!_inBound(pt))
                    component.outbound();
                else
                    component.inbound()
            }
        }
    }

    onEnabledChanged:  {
        _destroyMouseArea();
        if (enabled) {
            _setupMouseArea();
        }
    }

    Component.onCompleted: {
        if (enabled)
            _setupMouseArea();
    }

    Component.onDestruction: {
        _destroyMouseArea();
    }

}

使用

    Rectangle{
        id: rect1
        anchors.centerIn: parent
        width:60
        height: 20
        color: "gray"

        radius: 4

        InverseMouseArea{
            anchors.fill: parent

            enabled: true

            onOutbound: {
                tip.visible = false
            }
            onInbound: {
                tip.visible = true
            }
        }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值