QML笔记——MouseArea的覆盖区域

问题摘要

初学QML,今天发现一个奇怪的现象,调用MouseArea的位置不同,结果不同。

1、一个简单的qml示例

Rectangle {
    id: root
     320
    height: 200
    Button{
        anchors.centerIn:parent;
        text:"Quit";
        style:ButtonStyle{
            background:Rectangle{
                implicitWidth:170;
                implicitHeight:50;
                border.control.pressed ? 5 : 1;
                border.color:(control.hovered||control.pressed) ? "green" :"red";
            }
        }
        onClicked:{
            console.log("Quit");
            //Qt.quit()
        }
    }
}

      正常效果如下:  

       

2、  添加MouseArea对象

Rectangle {
    id: root
     320
    height: 200
    Button{
        anchors.centerIn:parent;
        text:"Quit";
        style:ButtonStyle{
            background:Rectangle{
                implicitWidth:170;
                implicitHeight:50;
                border.control.pressed ? 5 : 1;
                border.color:(control.hovered||control.pressed) ? "green" :"red";
            }
        }
        onClicked:{
            console.log("Quit");
            //Qt.quit()
        }
    }

    MouseArea{
        anchors.fill:parent;
        acceptedButtons: Qt.LeftButton | Qt.RightButton 
        onDoubleClicked:{
            console.log("DoubleButton");
        }
        onClicked:{
            if(mouse.button == Qt.LeftButton){
                console.log("LeftButton");
            }else if(mouse.button == Qt.RightButton){
                console.log("RightButton");
                Qt.quit();
            }
        }
    }
}

    左键点击Quit 按钮没有反应:按钮宽度没有变化,不会输出console.log("Quit");   而输出console.log("LeftButton")。

    

3、调换MouseArea位置:

Rectangle {
    id: root
     320
    height: 200

    MouseArea{
        anchors.fill:parent;
        acceptedButtons: Qt.LeftButton | Qt.RightButton 
        onDoubleClicked:{
            console.log("DoubleButton");
        }
        onClicked:{
            if(mouse.button == Qt.LeftButton){
                console.log("LeftButton");
            }else if(mouse.button == Qt.RightButton){
                console.log("RightButton");
                Qt.quit();
            }
        }
    }
    
    Button{
        anchors.centerIn:parent;
        text:"Quit";
        style:ButtonStyle{
            background:Rectangle{
                implicitWidth:170;
                implicitHeight:50;
                border.control.pressed ? 5 : 1;
                border.color:(control.hovered||control.pressed) ? "green" :"red";
            }
        }
        onClicked:{
            console.log("Quit");
            //Qt.quit()
        }
    }
}

    Quit按钮可以正常反应:

     

 总结

  MouseArea的调用,有先后优先级,后续的设置会覆盖前面的设置。局部的调用没有被触发。
原文地址:https://www.cnblogs.com/daiker/p/QML_MouseArea.html