Instantiate inline Component without Loader

2019-08-02 02:26发布

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.

标签: qt qml qtquick2
2条回答
Root(大扎)
2楼-- · 2019-08-02 02:46

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.

查看更多
叛逆
3楼-- · 2019-08-02 03:06

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");
    }
}
查看更多
登录 后发表回答