Unsolved using QList from c++ backend in QML
-
Hello Guys,
i´ve tried to put my own backend c++ code in a QML model.
i write a new class with this code:class DataObject : public QObject { Q_OBJECT Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged) Q_PROPERTY(QString detailText READ detailText WRITE setDetailText NOTIFY detailTextChanged) ...
i add then with:
QList dataList;
dataList.append(new DataObject(chat->kon[i]->getname(), QVariant(ia).toString()));a new QList.
so far so good.
Now i add in the main.cpp with:engine.rootContext()->setContextProperty("modelContact", QVariant::fromValue(cont->dataList));
a modelContact property.
so in the example code it´s in the qml code the following area that i want to change:
// Model should be loaded from your messaging backend // model: [ // { text: "Tom McEloy", detailText: "Sorry for the late reply ...", image: Qt.resolvedUrl("../../assets/portrait0.jpg") }, // { text: "Leah Douglas", detailText: "Hahaha :D", image: Qt.resolvedUrl("../../assets/portrait1.jpg") } // ]
so like the comment i want to load the model from the backend, so i try:
model: modelContact
but i get no text or detailtext, where is the problem?
-
Hi,
Are you following the Using C++ Models with Qt Quick Views chapter of Qt's documentation ?
-
yeah i used exactly this documentation.
i think that the model is correctly loaded, but how can i change this code// Model should be loaded from your messaging backend // model: [ // { text: "Tom McEloy", detailText: "Sorry for the late reply ...", image: Qt.resolvedUrl("../../assets/portrait0.jpg") }, // { text: "Leah Douglas", detailText: "Hahaha :D", image: Qt.resolvedUrl("../../assets/portrait1.jpg") } // ]
with the modelData object from the Using C++ Models with Qt Quick Views chapter documentation.
if i try this codemodel : [ { text: model.modelData.text } ]
nothing happen...
-
Then I think you have to follow the Exposing C++ Data Model to QML.
-
@Allerknappe
QML can convert QLists using basic data types. For lists containing Items or QObjects you need to implement a QQuickListProperty property. See the birthday party example as reference. -
A
QQmlListProperty
is needed when you want to populate a list declaratively from QML.When you data is coming from c++, you can expose a list with a
QList<QObject*>
(but not aQList<DerivedFromQObject*>
), aQVarantList
or aQAbstractItemModel
(aQAbstractListModel
generally). The latter is more generic, allow more fine grained changes to the model and is more type safe.Implementing a
QAbstractItemModel
can be a tedious task, if you don't want to do it yourself I recommend one of those 2 librairies : http://gitlab.unique-conception.org/qt-qml-tricks/qt-qml-models & https://github.com/benlau/qsyncable