Quantcast
Channel: Qt DevNet forums: Qt Quick 1283365070**
Viewing all articles
Browse latest Browse all 4972

Passing QLists to QML

$
0
0
I’ll provide you a simple and easy to understnad sample Model i just made: model.h #include <QModelIndex>   class Model : public QAbstractListModel {         Q_OBJECT     public:         Model(QObject *parent);         ~Model();         int rowCount(const QModelIndex &parent = QModelIndex()) const;         int columnCount(const QModelIndex &parent = QModelIndex()) const;         QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;         enum Roles {                 NameRole = Qt::UserRole         };         QHash<int, QByteArray> roleNames() const {             QHash<int ,QByteArray> roles;             roles[NameRole] = "name";             return roles;         } }; model.cpp #include "Model.h" #include <QImage>   Model::Model(QObject *parent)     :QAbstractListModel(parent) { }   int Model::rowCount(const QModelIndex &parent) const {     return 4; } int Model::columnCount(const QModelIndex &parent) const {     return 2; } QVariant Model::data(const QModelIndex &index, int role) const {     if(role == NameRole)     {         return QString("Row%1, Column%2")                 .arg(index.row() + 1)                 .arg(index.column() +1);     }     return QVariant(); } Model::~Model(){   } This one can return a QString on request. It works fine if you pass it as a Model, it also should work if you add multiple of these into a QList<Model> and pass the QList to QML. I’ve set my a customrole in enum Roles {}. You can set as many roles as you want, just split them with a comma. I’ve set an let’s call it “alias” for my roles which will replace the QML propertyname you pass with the given role in the QHash<int, QByteArray>. Feel free to ask if you’ve got still some Questions.

Viewing all articles
Browse latest Browse all 4972

Trending Articles