初学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));
}
}
}
作者:91黑白格
来源:CSDN
原文:https://blog.csdn.net/heibaige/article/details/20641729
版权声明:本文为博主原创文章,转载请附上博文链接!