Say I've created an object with an id foo
. How far is the object visible by the name foo
? Everywhere in the current file? Everywhere in the current directory? Or what?
I read the QML documentation on scope but I didn't find info on this there.
Say I've created an object with an id foo
. How far is the object visible by the name foo
? Everywhere in the current file? Everywhere in the current directory? Or what?
I read the QML documentation on scope but I didn't find info on this there.
I found the answer in the id attribute documentation.
It says:
An object can be referred to by its
id
from anywhere within the component scope in which it is declared.
And "component scope" is defined in the scope documentation page
Using id
s to reference objects in a single source is all fine and dandy, but there is more to the story. id
s will also resolve down the object tree:
ApplicationWindow {
id: main
visible: true
width: 600
height: 300
property int test: 667
Obj { }
}
// Obj.qml
Item {
Obj2 {}
}
// Obj2.qml
QtObject {
Component.onCompleted: console.log(main.test)
}
As this example illustrates, the main
id
resolves from Obj2
that is created in Obj
that is created in main.qml
. In this aspect the id works very much like dynamic scope properties, with one notable exception, dynamic scope properties will only work if they are declared in the root object of a particular source, whereas the id
will resolve regardless of which object it is declared in, as long as it is in that source and of course, as long as it is not shadowed. I guess internally they do end up sort of transferred to the root object, as they become attributes for that component. Common logic dictates lookup performance would be similar to that of dynamic properties. To further reinforce the similarity with dynamic scope properties, both are not possible to chain and only resolve from the particular qml file. You cannot someObject.someDynamicScopeProperty
just like you cannot someObject.someId
, even if both the property and the id
are resolvable from within SomeObject
.
This is actually a lot more useful than it may appear initially. It will allow to reference objects down a known tree branch without the need to go back and meticulously interface properties or aliases in order to expose the branch structure for lookups. This is also a very good reason to use meaningful and unique identifiers for id
s, rather than using id: root
for the root object of every qml file.