Nulik Nulik - 26 days ago 15
C++ Question

Integrating your own QT C++ data model with QML

I am having problems exposing my C++ data model to a ListView in QML. QML can't find the properties of each row.

I have this class (QT 5.7):

class Identity : public QObject
{
Q_OBJECT
Q_PROPERTY(QString email READ email WRITE setEmail NOTIFY emailChanged);
Q_PROPERTY(QString password READ password WRITE setPassword NOTIFY passwordChanged);
...
}


And I have a model class that stores Identity objects:

class Identities: public QAbstractItemModel {
Q_OBJECT

private:
QMap<QString,Identity*> identities_map;
...
}


I'm also registering it in main.cpp:

qmlRegisterType<Identities>("project_identities",1,0,"Identities");


My main.qml has these definitions:

Identities {
id: identidades
}
ListView {
anchors.fill: parent
model: identidades
delegate: Row {
Text { text: "Email: " + model.email}
}
}


Now the problem is, when I display the list of emails and passwords, this is the output:

Email: undefined


What I am missing ?
When I debug my code with the debugger, the only method that is being executed is Identities::rowCount(). The Identities::index() is not executed, nor Identities::data().

Where could the problem be?

Answer

Does your model object have a property named email? If not, that would explain why it says that it is undefined. Saying model.email is like saying identidades.email. It is not a reference to the model item object, but to the model object.

That's not how you use roles, the item role is not a property of the list object, you don't do model.role you just do role.

So, providing the roles in the model are properly implemented, all you need to do is:

Text { text: "Email: " + email}.