问题
ApplicationWindow {
id: root
property string rootName: "--rootName"
visible: true
width: 800
height: 400
title: qsTr("WatchFace Maker")
WatchLcd{
property string watchLcdInApp: "watchLcdInApp"
id: watchLcd
}
TextAdder{
id: textAdder
Component.onCompleted: {
console.log("APP: ", root.watchLcd.watchLcdInApp)//#Error!!! remove root, it works.
}
}
}
I want to know:
Why it doesn't work when I add root id in above commented line?
How do children component access sibling component's property if children component is created from a XXX.qml file?
回答1:
The id property is a "special kind" of property, it is only resolved at "code time" and cannot be resolved during runtime.
root.watchLcd will not work because watchLcd is an id, and as such it can't be resolved with root.watchLcd
The id also logically works only in that particular source, and you only need that particular id regardless of the structure of the object tree, you don't need its parent id as in root.watchLcd
If you want to access a specific object from another file, naturally, this can't happen through its id. You can either use a property or a function for it:
//SomeItem.qml
Item {
property alias text : obj.text
Item {
id: obj
property string text
}
property Item object : obj
function getObj() { return obj }
}
/main.qml
Window {
visible: true
SomeItem {
id: item
text: "someText"
}
SomeItem {
Component.onCompleted: {
//console.log(item.obj.text) // TypeError: Cannot read property 'text' of undefined
console.log(item.object.text) // someText
console.log(item.getObj().text) // someText
}
}
}
Also, note how the property alias works - it may be useful in many cases, if all you need to access is a nested object's property you can expose it with an alias without needing access to the object externally.
来源:https://stackoverflow.com/questions/36736573/qml-cannot-read-property-xxx-of-undefined