Window例如,我想知道 a是否有一些子元素。是否有可能得到哪个孩子在其MouseArea当前的 x 和 y之下?
解决这个问题的策略是使用 方法将鼠标获得的坐标转换为全局坐标mapToGlobal(),然后使用 方法mapFromGlobal()将这些全局坐标转换为每个 Item 的局部,最后用于contains()验证点是否在 Item 内部。要获得孩子,您必须使用该children()方法。
Window {
id: window
visible: true
width: 640
height: 480
function itemsFromGlobalPosition(root, globalPos){
var items = []
for(var i in root.children){
var children = root.children[i]
var localpos = children.mapFromGlobal(globalPos.x, globalPos.y)
if(children.contains(localpos)){
items.push(children)
}
items = items.concat(itemsFromGlobalPosition(children, globalPos))
}
return items;
}
MouseArea{
id: ma
anchors.fill: parent
onClicked: {
var results = itemsFromGlobalPosition(window.contentItem, ma.mapToGlobal(mouseX, mouseY))
console.log("results: ", results)
}
}
...
}
Run Code Online (Sandbox Code Playgroud)