如何访问 Loader 的 sourceComponent 中的 QML 对象?

如何访问 Loader 的 sourceComponent 中的 QML 对象?

问题描述:

我可能需要从某个外部函数读取或写入 LoadersourceComponent 的某些属性.

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

如何访问这个LoadersourceComponent中对象的属性x?

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

当您需要向外部公开内部对象/属性时,您应该创建一个 别名.

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