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++.
import QtQuick 2.0;in the string passed toQt.createQmlObjectcomponent = Qt.createQmlObject("import QtQuick 2.4; import org.qtproject.models 1.0; Car { id: car_1; carName : \"H1\"; carBrand : \"Hummer\"; carPrice : 125000; }", parent, "dynamicSnippet1");and I getqrc:/main.qml:58: Error: Invalid write to global property "component"when the code gets executed...var component = Qt.createQmlObjectinstead ofcomponent = Qt.createQmlObject?