As far as I know, they both do the same thing: create a QML element and place it in the hierarchy of QML elements. My question however, is: what benefit do you gain from using one over the other? Wouldn't Qt.createComponent().createObject(), on the contrary to the QML documentation, logically be less efficient, as it has to load the file and parse it, rather than Qt.createQmlObject() which just reads the parameters and also parses it?
-
Possibly related: When should Loader be preferred over createQmlObject and vice versa - QML?.musicamante– musicamante2025-09-30 17:05:18 +00:00Commented Sep 30 at 17:05
-
1The link from @musicamante should be helpful to you. Also, it would be helpful for you to understand the difference between a Component and an Object. They're not the same thing.JarMan– JarMan2025-09-30 20:44:12 +00:00Commented Sep 30 at 20:44
-
@JarMan I meant creating a component then creating the object from that component.none2– none22025-10-01 04:11:54 +00:00Commented Oct 1 at 4:11
1 Answer
I would consider Qt.createComponent and Qt.createQmlObject only as a last resort.
The first option should be a Repeater or ListView with a model, since the QML engine dynamically creates and destroys objects as the model updates, and parameters can be passed through the model.
The second option is Qt.createComponent, which allows you to inject parameters via an object.
The last option to consider is Qt.createQmlObject, as it requires parsing QML text at runtime and embedding parameters directly into the QML code.
All approaches have their merits, depending on your use case.
import QtQuick
import QtQuick.Controls
Page {
// Version 0: Direct instance
RedSquare { x: 50; y: 50 }
// Version 1: With model
Repeater {
model: ListModel { id: listModel }
delegate: RedSquare {
x: model.x
y: model.y
}
}
Component.onCompleted: {
// Version 1: With model (cont)
listModel.append( { x:100, y:50 } );
// Version 2: With Qt.createComponent
var c = Qt.createComponent("RedSquare.qml");
c.createObject(this, { x:150, y: 50 } );
// Version 3: With Qt.createQmlObject
Qt.createQmlObject("RedSquare { x: 200; y: 50 }", this, "mySnippet");
}
}
// RedSquare.qml
import QtQuick
import QtQuick.Controls
Rectangle {
width: 20
height: 20
color: "red"
}
You can Try it Online!