#include "MyListModel.h" #include "MyStruct.h" MyListModel::MyListModel(QObject *parent) : QAbstractListModel(parent) , m_myStructs() { } MyListModel::~MyListModel() { qDeleteAll(m_myStructs); } int MyListModel::rowCount(const QModelIndex &parent) const { // For list models only the root node (an invalid parent) should return the list's size. For all // other (valid) parents, rowCount() should return 0 so that it does not become a tree model. return parent.isValid() ? 0 : m_myStructs.length(); } QVariant MyListModel::data(const QModelIndex &index, int role) const { if (!checkIndex(index, CheckIndexOptions( CheckIndexOption::IndexIsValid | CheckIndexOption::ParentIsInvalid))) { return QVariant(); } const int row(index.row()); if (row >= rowCount(index.parent())) return QVariant(); const int column(index.column()); if (column >= 1) return QVariant(); switch(role) { case Role::Data: return m_myStructs.at(row)->data; case Role::DateCreated: return m_myStructs.at(row)->dateCreated; case Role::DateModified: return m_myStructs.at(row)->dateModified; case Role::Name: return m_myStructs.at(row)->name; case Role::Icon: return m_myStructs.at(row)->icon; case Role::ID: return m_myStructs.at(row)->id; } return QVariant(); } QHash MyListModel::roleNames() const { static QHash roleNames( { { Role::Data, QByteArrayLiteral("d") }, { Role::DateCreated, QByteArrayLiteral("DateCreated") }, { Role::DateModified, QByteArrayLiteral("DateModified") }, { Role::Name, QByteArrayLiteral("Name") }, { Role::Icon, QByteArrayLiteral("Icon") }, { Role::ID, QByteArrayLiteral("id") } }); return roleNames; } void MyListModel::setMyStructs(const QList &structs) { if (m_myStructs == structs) return; beginResetModel(); m_myStructs = structs; endResetModel(); }