universallistmodel.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #ifndef UNIVERSALLISTMODEL_H
  2. #define UNIVERSALLISTMODEL_H
  3. #include <QAbstractListModel>
  4. #include <QObject>
  5. #include <QList>
  6. #include <QHash>
  7. #include <QPointer>
  8. #include <QMetaProperty>
  9. #include <QMetaObject>
  10. #include <QDebug>
  11. template <typename T>
  12. class UniversalListModel : public QAbstractListModel
  13. {
  14. public:
  15. ~UniversalListModel() {
  16. foreach (QPointer<T> value, m_container) {
  17. delete value.data();
  18. }
  19. m_container.clear();
  20. }
  21. int rowCount(const QModelIndex &parent) const {
  22. Q_UNUSED(parent)
  23. return m_container.count();
  24. }
  25. QHash<int, QByteArray> roleNames() const {
  26. if(s_roleNames.isEmpty()) {
  27. int propertyCount = T::staticMetaObject.propertyCount();
  28. for(int i = 0; i < propertyCount; i++) {
  29. s_roleNames.insert(Qt::UserRole + i, T::staticMetaObject.property(i).name());
  30. }
  31. }
  32. return s_roleNames;
  33. }
  34. QVariant data(const QModelIndex &index, int role) const
  35. {
  36. int row = index.row();
  37. if(row < 0 || row >= m_container.count()) {
  38. return QVariant();
  39. }
  40. T* dataPtr = m_container.at(row).data();
  41. return dataPtr->property(s_roleNames.value(role));
  42. }
  43. bool add(T* value) {
  44. Q_ASSERT_X(value != nullptr, fullTemplateName(), "Trying to add member of NULL");
  45. if(m_container.indexOf(value) >= 0) {
  46. #ifdef DEBUG
  47. qDebug() << fullTemplateName() << "Member already exists";
  48. #endif
  49. return false;
  50. }
  51. beginInsertRows(QModelIndex(), m_container.count(), m_container.count());
  52. m_container.append(QPointer<T>(value));
  53. endInsertRows();
  54. return true;
  55. }
  56. void remove(T* value) {
  57. Q_ASSERT_X(value != nullptr, fullTemplateName(), ": Trying to remove member of NULL");
  58. int valueIndex = m_container.indexOf(value);
  59. if(valueIndex >= 0) {
  60. beginRemoveRows(QModelIndex(), valueIndex, valueIndex);
  61. m_container.removeAt(valueIndex);
  62. endRemoveRows();
  63. }
  64. }
  65. protected:
  66. UniversalListModel(QObject* parent = 0) : QAbstractListModel(parent) {}
  67. QList<QPointer<T>> m_container;
  68. static QHash<int, QByteArray> s_roleNames;
  69. private:
  70. #ifdef DEBUG
  71. static QByteArray fullTemplateName() { //Debug helper
  72. return QString("UniversalListModel<%1>").arg(T::staticMetaObject.className()).toLatin1();
  73. }
  74. #endif
  75. };
  76. template<typename T>
  77. QHash<int, QByteArray> UniversalListModel<T>::s_roleNames;
  78. #endif // UNIVERSALLISTMODEL_H