Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Dynamic qml object creation from c++ code
FedorKozlov last edited by aha_1980
I want to strongly separate app logic on c++ and gui on qt quick. I have map (2d array) of cells with deferent properties, which will be modified during app lifecycle. Size of map also can vary. I have cell.qml that describes how cell should look like. But i don't understand how to dynamically create certain amout of cells in qml from cpp code. For example, at initialization, when i create c++ object i need corresponding qml object to be created as well.
oria66 last edited by
From my point of view, if you want to trigger an action from the c++ side to qml side, you must use the signal/slot mechanism. Otherwise, you should have the object of your c++ class in qml, and if the user triggers an event, you provide a method to respond that action if it is required backend activity.
If you provide some code it would nice, your explication it is kind of abstract.
For your usecase you should expose a QAbstractItemModel to your QML layer.
Then in QML you would use a
Repeaterthat will instantiate a
Cellfor each row of your model.
Tom_H last edited by
It's much easier to do QML tasks in QML. Create a QML method to do it and call it from C++ with QMetaObject::invokeMethod().
FedorKozlov last edited by
Thank you all for your answers!
I believe as @GrecKo said QAbstractItemModel is what i really need.
Though, as i found here http://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html
QAbstractItemModel presents a hierarchy of tables, but the views currently provided by QML can only display list data. In order to display the child lists of a hierarchical model, use the DelegateModel QML type
@FedorKozlov There's no need for a DelegateModel in your case.
You can display table data with a
TableView, but you can also display data in a table like fashion with a
GridViewor even a
Repeaterwith the delegates positionning themselves.
If I guessed right you are trying to do some kind of Game of Life in Qt Quick.
The position of your cells is just data, you don't really need a table model.
FedorKozlov last edited by FedorKozlov
@GrecKo You're right! I am defenetly doing some kind of Game of Life)
I've managed to create a map, using GridView and QAbstractListModel like in this video.
I also understood how to pass values using model's roles. Now I'm trying to find out how to pass user defined classes through QVariant. I guess i also should register my 'Cell' class with qmlRegisterType<>