QML筆記——MouseArea的覆蓋區域


問題摘要

初學QML,今天發現一個奇怪的現象,調用MouseArea的位置不同,結果不同。

1、一個簡單的qml示例

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

      正常效果如下:  

       

 

 

2、  添加MouseArea對象

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

    Quit按鈕可以正常反應:

     

 

 總結

  MouseArea的調用,有先后優先級,后續的設置會覆蓋前面的設置。局部的調用沒有被觸發。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM