1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- #ifndef UNIVERSALLISTMODEL_H
- #define UNIVERSALLISTMODEL_H
- #include <QAbstractListModel>
- #include <QObject>
- #include <QList>
- #include <QHash>
- #include <QPointer>
- #include <QMetaProperty>
- #include <QMetaObject>
- #include <QDebug>
- template <typename T>
- class UniversalListModel : public QAbstractListModel
- {
- public:
- ~UniversalListModel() {
- foreach (QPointer<T> value, m_container) {
- delete value.data();
- }
- m_container.clear();
- }
- int rowCount(const QModelIndex &parent) const {
- Q_UNUSED(parent)
- return m_container.count();
- }
- QHash<int, QByteArray> roleNames() const {
- if(s_roleNames.isEmpty()) {
- int propertyCount = T::staticMetaObject.propertyCount();
- for(int i = 0; i < propertyCount; i++) {
- s_roleNames.insert(Qt::UserRole + i, T::staticMetaObject.property(i).name());
- }
- }
- return s_roleNames;
- }
- QVariant data(const QModelIndex &index, int role) const
- {
- int row = index.row();
- if(row < 0 || row >= m_container.count()) {
- return QVariant();
- }
- T* dataPtr = m_container.at(row).data();
- return dataPtr->property(s_roleNames.value(role));
- }
- bool add(T* value) {
- Q_ASSERT_X(value != nullptr, fullTemplateName(), "Trying to add member of NULL");
- if(m_container.indexOf(value) >= 0) {
- #ifdef DEBUG
- qDebug() << fullTemplateName() << "Member already exists";
- #endif
- return false;
- }
- beginInsertRows(QModelIndex(), m_container.count(), m_container.count());
- m_container.append(QPointer<T>(value));
- endInsertRows();
- return true;
- }
- void remove(T* value) {
- Q_ASSERT_X(value != nullptr, fullTemplateName(), ": Trying to remove member of NULL");
- int valueIndex = m_container.indexOf(value);
- if(valueIndex >= 0) {
- beginRemoveRows(QModelIndex(), valueIndex, valueIndex);
- m_container.removeAt(valueIndex);
- endRemoveRows();
- }
- }
- protected:
- UniversalListModel(QObject* parent = 0) : QAbstractListModel(parent) {}
- QList<QPointer<T>> m_container;
- static QHash<int, QByteArray> s_roleNames;
- private:
- #ifdef DEBUG
- static QByteArray fullTemplateName() { //Debug helper
- return QString("UniversalListModel<%1>").arg(T::staticMetaObject.className()).toLatin1();
- }
- #endif
- };
- template<typename T>
- QHash<int, QByteArray> UniversalListModel<T>::s_roleNames;
- #endif // UNIVERSALLISTMODEL_H
|