Create a list model in c++ with roles
-
Hi there,
I need to create a model using c++ for a table in QML. When I create the model using qml it just works:
@
ListModel {
id: replacementsModel
ListElement {
original: "aaa"
replacement: "zzz"
}
ListElement {
original: "hello"
replacement: "bye"
}
ListElement {
original: "yes"
replacement: "no"
}
}
@But I have no clue how to do create the model using c++. Can anybody help me please??
-
To start with you can read "qtquick-modelviewsdata-cppmodels":http://qt-project.org/doc/qt-5/qtquick-modelviewsdata-cppmodels.html
To add new roles you need to reimplement "roleNames":http://qt-project.org/doc/qt-5/qabstractitemmodel.html#roleNames.
More example can be found in <QtDir>/Examples/Qt-5.3/quick/models if you are using Qt 5.3 -
I addition to the doc page p3c0 referenced above, your starting class will be "QAbstractListModel":http://doc.qt.digia.com/qt-5.2/qabstractlistmodel.html . Extend that class properly and you can build your model with the apprioate roles.
-
@Implement QAbstractListModel like following.
class PeopleModel : public QAbstractListModel
{
Q_OBJECT
public:enum PersonRoles { NameRole = Qt::UserRole + 1, IdRole, PinRole, AddressRole };
...
...
QHash<int, QByteArray> roleNames() const;
}
Implementation
QHash<int, QByteArray> PeopleModel::roleNames() const {
QHash<int, QByteArray> role;role[NameRole] = "Name"; role[IdRole] = "Id"; role[PinRole] = "Pin"; role[AddressRole] ="Address"; return role;
}
In addition to all the above, you need to implement the necessary function of QAbstractListModel
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;QVariant data(const QModelIndex &index, int role) const;@
If you need complete source code dump, do let me know. I can send.
-
If you have your data in a SQL database you should consider using "QSqlQueryModel":http://qt-project.org/doc/qt-5/QSqlQueryModel.html or "QSqlTableModel":http://qt-project.org/doc/qt-5/qsqltablemodel.html.
The process to implement the model in C++ is similar to the example above.