How to access the QML object inside the Loader's sourceComponent?
Asked Answered
S

1

14

I may need to read or write to some of the properties of the Loader's sourceComponent from some outside function.

What is the way to access the property x of the object inside this Loader's sourceComponent?

 import QtQuick 2.0

 Item {
     width: 200; height: 200

     Loader {
         anchors.fill: parent
         sourceComponent: rect
     }

     Component {
         id: rect
         Rectangle 
         {
             width: 50
             height: 50
             color: "red"
             property int x
         }
     }
 }
Selfdriven answered 6/2, 2015 at 7:6 Comment(0)
C
19

When you need to expose an inner object/property to the outside, you should create an alias to it.

import QtQuick 2.0

 Item {
     width: 200; height: 200
     property alias loaderItem: loader.item

     Loader {
         id: loader
         anchors.fill: parent
         sourceComponent: rect
     }

     Component {
         id: rect
         Rectangle 
         {
             width: 50
             height: 50
             color: "red"
             property int x
         }
     }
 }
Chrissy answered 6/2, 2015 at 9:42 Comment(6)
How does this help in accessing x ?Thigmotaxis
@Thigmotaxis you can access it via loaderItem.xChrissy
It doesn't seem to work in case of external files, with a loader.source:"something.qml". I'll make a few experiments and post a new question if necessary.Thigmotaxis
Sorry, it was my mistake. It works even with an item which doesn't contain the loader.Thigmotaxis
It is completely unnecessary to have a root item and then a loader in it, the loader should be the root rather than wasting memory on an extra item, an id and a property alias.Kohler
DTech:The difference is encapsulation: By making a Item the root component you get to choose what properties of the new component you want to expose. If you make the loader the root component then you expose all the loaders properties not just the item, this may not be what you want.Billyebilobate

© 2022 - 2024 — McMap. All rights reserved.