问题
I'm wondering why for Item this works:
Item {
id: root
width: 640
height: 480
MouseArea {
anchors.fill: (root or parent. It doesn't matter)
onClicked: console.log("clicked")
}
}
But for Window it doesn't. Only anchoring by parent will work, but for anchoring by id it will fail.
回答1:
According to the documentation, anchors.fill requires the argument either to be or to identify an Item-derived object.
From here you can follow the inheritance chain of Window and see that it is not actually an Item.
Moreover, from here you can see that:
If you assign an Item to the data list, it becomes a child of the Window's contentItem, so that it appears inside the window.
where for the contentItem we have that:
This attached property holds the invisible root item of the scene or null if the item is not in a window.
Because of that, it makes sense what you are observing:
- the
idof theWindowdoes not identify anItem
→ anchoring byidresults in an error - the
parentis actually the hiddenItem-derivedcontentItemto which each child ofWindowis automatically parented
→ anchoring byparentcorrectly works
来源:https://stackoverflow.com/questions/34527083/difference-in-qml-between-window-and-item-in-parent-children-relationship