Search code examples
c++qtqmlqtquick2qt-quick

Dynamically create C++ object from QML


I want to dynamically create a C++ object from QML. I created a QObject derived class named Car and exposed it to QML using qmlRegisterType<Car>("org.qtproject.models", 1, 0, "Car");. Inside QML I am able to instantiate a Car object like this:

Car {
    id : car_1
    carName : "H1"
    carBrand : "Hummer"
    carPrice : 125000
} 

and then use the car_1 object and pass it back to C++ with ease if I need to. But what I would like is to create a Car object dynamically in QML, so I can pass it back to C++.

I tried:

MouseArea
{
    anchors.fill: parent
    onClicked: {
        component = Qt.createQmlObject("Car { id: car_1; carName : \"H1\"; carBrand : \"Hummer\"; carPrice : 125000; }",
                                       parent, "dynamicSnippet1");

        myCarModel.appendRowFromQml(component);
    }
}

but no luck. With the static approach, works fine:

MouseArea
{
    anchors.fill: parent
    onClicked: {
        myCarModel.appendRowFromQml(car_1);
    }
}

Is there a way to dynamically create a C++ object from the QML side? I also couldn't use Qt.createComponent because there is no *.qml file in which Car is defined, as Car was defined in C++.


Solution

  • As I said in the comments, the problem is the variable component, which doesn't exist at that time.

    So to fix the problem it is enough to replace the following code:

    onClicked: {
        component = Qt.createQmlObject(...);
    

    by:

    onClicked: {
        var component = Qt.createQmlObject(...);