Reputation: 954
I was wondering if a Window
, for example ,has some child elements. Would it be possible to get which child is under its MouseArea
's current x and y?
Upvotes: 3
Views: 764
Reputation: 243897
The strategy to solve this problem is to convert the coordinate obtained by the mouse to global coordinates using the method mapToGlobal()
, then use the method mapFromGlobal()
to convert those global coordinates to local for each Item, and finally use contains()
to verify if the point is inside the Item. To obtain the children you must use the children()
method.
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)
}
}
...
}
Upvotes: 5