【初學qml之麻煩篇】:(1)依據座標,判斷某處的Item

    初學qml,需要實現單擊鼠標,使所點擊的Rectangle(有多個Rectangle)獲得焦點,並改變顏色。

    這個實現起來呢並不麻煩,在每個Rectangle中加入MouseArea實現即可,但是我並不想這樣做,想只用一個MouseArea,這就需要判斷點擊的是哪個,於是我想通過鼠標點擊的座標判斷,搜索無果但是找到了一個函數childAt(),於是乎依據此函數小小的實現了下。

    childAt用法:

    Item::childAt ( realx, realy)

    Returns the visible child item at point (x, y), which is in this item's coordinate system, ornull if there is no such item.

   其它:

   鼠標當前座標  mouseX , mouseY

   

代碼如下:

Rectangle {

    width: 200; height: 200; color: "black"

    Grid {

        id: cl

        columns: 2

        spacing: 6

        Rectangle {

            id: r1

            width: 80; height: 80

            color: "yellow"

            opacity: focus ? 1 : 0.5

            focus: true

            //KeyNavigation.right: r2

            //KeyNavigation.down: r3

        }

        Rectangle {

            id: r2

            width: 80; height: 80

            color: "lightblue"

            opacity: focus ? 1 : 0.5

            //KeyNavigation.right: r3

            //KeyNavigation.down: r4

        }

        Rectangle {

            id: r3

            width: 80; height: 80

            color: "green"

            opacity: focus ? 1 : 0.5

            //KeyNavigation.right: r4

            //KeyNavigation.up: r1

        }

        Rectangle {

            id: r4

            width: 80; height: 80

            color: "purple"

            opacity: focus ? 1 : 0.5

            //KeyNavigation.right: r1

            //KeyNavigation.up: r2

        }

    }

    MouseArea {

        anchors.fill: parent

        onClicked: {

            if(cl.childAt(mouseX , mouseY))

                cl.childAt(mouseX , mouseY).focus = true;

            //console.log(mouseX,mouseY);

            //console.log(cl.childAt(mouseX , mouseY));

        }

    }

}



  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章