1

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?

3
  • Possibly related: When should Loader be preferred over createQmlObject and vice versa - QML?. Commented Sep 30 at 17:05
  • 1
    The 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. Commented Sep 30 at 20:44
  • @JarMan I meant creating a component then creating the object from that component. Commented Oct 1 at 4:11

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.