Sharing component instance with nested components
-
Suppose I need to access a QML component instance in two or more other components of my application. The accessed component needs to be the same instance because it contains state. One obvious place to create it is at the top level, in an
ApplicationWindow
for example.The accessing components are quite deeply nested, however, and implementations are factored out into separate component files.
My question is: what is the recommended way to make the shared instance available to the other components?
ApplicationWindow { id: root SharedComponent { id: shared } A {} // a nested component of A needs "shared" B {} // a nested component of B needs "shared"
I believe ids are somewhat accessible from child components even if in a different file, so potentially I could just reference
shared
. I am not sure it is this simple though and am not clear about the accessibility rules. In any case I don't really like the idea of simply relying on an id as it feels quite brittle.Another alternative is to expose a property in the nested components and assign from the parent, but the problem there is that the components that actually need
shared
are nested quite deeply so that there is going to be a chain of such properties that need to be defined and assigned. That doesn't feel right either.Surprisingly I have not hit this issue before now, but I guess I can't be the first who has needed such an arrangement. Is there a recommended/canonical approach to this?
-
For now, I have got the first approach I mentioned working. For this I have renamed the
ApplicationWindow
id to be a meaningful, "well known" name,appWindow
. I also needed to introduce aproperty alias
for theshared
id to make it accessible from child components.I am still interested in comments about what would be the recommended approach here.