Conditionally include component based on property value

佐手、 提交于 2019-12-02 01:57:33

Turned out to be fairly straightforward to implement a Loader. Example:

Item {
    id: team1Info

    Loader {
        id: team1ItemLoader
        property string name: model.team1Name
        property string logo: model.team1Logo

        source: (logo) ? "TeamLogoItem.qml" : "TeamItem.qml"
    }
}

In this example, name and logo then become available inside TeamLogoItem.qml or TeamItem.qml as properties.

The answer by @TommyBrunn only works if TeamItem.qml does not define any property you want to pass in. This means that:

  • You cannot use property alias in your component
  • You cannot supply any default value for such a property

Alternatively, you can use setSource() for a Loader to pass property values in to the loaded component:

// ### TeamItem.qml (and TeamLogoItem.qml, similarly)
Label {
  property alias name: text
  property string logo: "qrc:/images/logos/dummy.png"
}    
// ### main.qml
Item {
    id: team1Info

    Loader {
        Component.onCompleted: {
            var qml = model.team1Logo ? "TeamLogoItem.qml" : "TeamItem.qml";
            setSource( qml, { name:model.team1Name, logo:model.team1Logo } )
        }
    }
 }

You could also choose to pass different property values in—e.g. not pass in a logo to TeamItem.qml—based on the QML you are loading. They do not have to have the same interface.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!