Reputation: 7749
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 Loader
s as I am about polluting my file with lots of Loader
wrappers.
Upvotes: 2
Views: 1673
Reputation: 2232
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");
}
}
Upvotes: 2
Reputation: 7150
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.
Upvotes: 5