Instantiate inline Component without Loader

牧云@^-^@ 提交于 2019-12-11 04:21:09

问题


Is there a way of instantiating an inline Component (i.e. defined in the same file) without using a Loader? I'm less concerned about the performance impact of using Loaders as I am about polluting my file with lots of Loader wrappers.


回答1:


You can use a Repeater to create components without Loader. Or you can even use Qt.createComponent to do that.

Take a look at Qt Documentation about Dynamic Component Creation in QML

information and examples about Repeater can be found here

You can even create component from string on the fly:

Rectangle {
    id: appWindow
    width: 300; height: 300

    Component.onCompleted: {
      var newObject = Qt.createQmlObject('import QtQuick 2.0; Rectangle {color: "red"; width: 20; height: 20}',
                                       appWindow,
                                       "dynamicSnippet1");
    }
}



回答2:


I find that the Dynamic QML Object Creation from JavaScript page can be misleading.

There's no mention about using a declaratively created Component or using models instead. It mentions only Qt.createComponent or Qt.createQmlObject which are needlessly imperative (and relying on strings) most of the time.

I would advise using an inline Component with createObject() instead for more readable and maintainable code. Like so :

Rectangle {
    id: appWindow
    width: 300; height: 300

    Component {
        id: redRectComponent
        Rectangle {
            color: "red"
            width: 20
            height: 20
        }
    }

    Component.onCompleted: {
        var newObject = redRectComponent.createObject(appWindow);
    }
}

I'd use this method if I wanted to create a temporary object imperatively, like a popup for example.

If I were to create several of those objects, I'd most likely use a ListModel with a ListView/Repeater/Instantiator/... like so:

ListModel {
    id: rectModel
}

Column {
    Repeater {
        model: rectModel
        Rectangle {
            color: model.rectColor
            width: 20
            height: 20
        }
    }
}

Button {
    onClicked: rectModel.append({rectColor: "red"})
}

Here I don't even have to handle the the object creation, I just insert some data in the ListModel and the Repeater takes care of the instantiation of the delegates.



来源:https://stackoverflow.com/questions/45855962/instantiate-inline-component-without-loader

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