Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Creating QML elements at runtime
kuschky last edited by
Hello, I have some already existing QObject based classes representing some data I want display as graphic in QML.
For that I change my class defintion so that my classes now derived from QDeclarativeItem and providing a implementation for the paint method and make them accessible by qmlRegisterType.
class Car : public QDeclarativeItem
Q_PROPERTY(int wheels READ wheels WRITE setWheels NOTIFY wheelsChanged)
I'm now able to embed these objects into QML:
That's fine and works.
But is there a way to create those kinds of objects on the C++ side and add them on a dynamic way at runtime to a QML context or to replace an already existing QML element with them? What want to do is to add another Car Object / Element with id car3 or replace an existing Car element with a one created in C++?
Thanks & best regards Michael
dmcr last edited by
If the context that you associated to your QML contains an object car
@ Q_PROPERTY(Car car READ getCarte WRITE setCar NOTIFY carChanged)@
then when you update the object, the QML will be noticed
with the event carChanged
If you want many of them then you can use QDeclarativeListeProperty.
drixs last edited by
if i have QML declarations lets say Book.qml and Paper.qml, and i have set Book.qml as QDeclarativeView source.
how i can create and store some "paper" as child of "Book" on the C++ side at runtime?
thanks in advance :D
diro last edited by
Two solutions for add object to QML context:
The method 1 is good for few objects, and method 2 is good for object array.
For your case, if you want to the car(s) display in the Rectangle dynamically, I think "DataModel":http://doc.qt.nokia.com/latest/qdeclarativemodels.html#exposing-c-data-models-to-qml + "ListView":http://doc.qt.nokia.com/4.7-snapshot/qml-listview.html element would be the best solution.