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
         }
     }
 }

1 Answer 1

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
         }
     }
 }
Sign up to request clarification or add additional context in comments.

6 Comments

How does this help in accessing x ?
@vsz you can access it via loaderItem.x
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.
Sorry, it was my mistake. It works even with an item which doesn't contain the loader.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.