Unsolved Dynamic qml object creation from c++ code
-
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.
-
Hello @FedorKozlov.
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 aRepeater
that will instantiate aCell
for each row of your model. -
@FedorKozlov
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(). -
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 aGridView
or even aRepeater
with 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. -
@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<>