I tried to use the cities-standarditem of the Qt exemple and adapt it to my exemple. I have a strange result:
Here is my User class:
class User{
public:
User();
QString getFirstname() const;
void setFirstname(const QString &value);
QString getLastname() const;
void setLastname(const QString &value);
int getAge() const;
void setAge(int value);
private:
QString firstname;
QString lastname;
int age;
};
and i have declared a usermodel.h:
class UserModel: public QStandardItemModel
{
Q_OBJECT
public:
UserModel(QList<User> users, QObject *parent = Q_NULLPTR);
QHash<int, QByteArray> roleNames() const;
};
And here is the implementations of the constructor and the roleNames functions:
enum ItemRoles {
FirstnameRole,
LastnameRole,
AgeRole,
};
UserModel::UserModel(QList<User> users, QObject *parent) : QStandardItemModel(parent)
{
//this->setItemRoleNames(roleNames());
this->setColumnCount(3);
for (auto user: users) {
QStandardItem *item = new QStandardItem();
item->setData(user.getFirstname(), FirstnameRole);
item->setData(user.getLastname(), LastnameRole);
item->setData(user.getAge(), AgeRole);
appendRow(item);
}
setSortRole(FirstnameRole);
}
QHash<int, QByteArray> UserModel::roleNames() const
{
QHash<int, QByteArray> mapping = QStandardItemModel::roleNames();
mapping[FirstnameRole] = "firstname";
mapping[LastnameRole] = "lastname";
mapping[AgeRole] = "age";
return mapping;
}
My table view only show the last Role added with the function:
item->setData(user.getFirstname(), FirstnameRole);
If its the age lastly added, its the age showed... Any clues ?