【问题标题】:How to access the QML object inside the Loader's sourceComponent?如何访问 Loader 的 sourceComponent 中的 QML 对象?
【发布时间】:2015-02-06 07:06:26
【问题描述】:

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

访问这个LoadersourceComponent内部对象的属性x的方法是什么?

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

【问题讨论】:

    标签: qt qml qtquick2


    【解决方案1】:

    当您需要向外部公开内部对象/属性时,您应该为它创建一个alias

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

    【讨论】:

    • 这对访问x有什么帮助?
    • @vsz 你可以通过loaderItem.x访问它
    • 它似乎不适用于外部文件,loader.source:"something.qml"。如有必要,我会做一些实验并发布一个新问题。
    • 对不起,这是我的错误。它甚至适用于不包含加载器的项目。
    • DTech:区别在于封装:通过将 Item 作为根组件,您可以选择要公开的新组件的哪些属性。如果您将加载器设为根组件,那么您会公开所有加载器属性,而不仅仅是项目,这可能不是您想要的。
    猜你喜欢
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多