listmodel.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #ifndef LISTMODEL_H
  2. #define LISTMODEL_H
  3. #include <QAbstractListModel>
  4. #include <QList>
  5. #include <QVariant>
  6. /*
  7. * Source code from: http://cdumez.blogspot.com/2010/11/how-to-use-c-list-model-in-qml.html
  8. */
  9. class ListItem: public QObject {
  10. Q_OBJECT
  11. public:
  12. ListItem(QObject* parent = 0) : QObject(parent) {}
  13. virtual ~ListItem() {}
  14. virtual QString id() const = 0;
  15. virtual QVariant data(int role) const = 0;
  16. virtual QHash<int, QByteArray> roleNames() const = 0;
  17. signals:
  18. void dataChanged();
  19. };
  20. /***************************************************************************************************/
  21. class ListModel : public QAbstractListModel
  22. {
  23. Q_OBJECT
  24. public:
  25. explicit ListModel(ListItem* prototype, QObject* parent = 0);
  26. ~ListModel();
  27. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  28. QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
  29. void appendRow(ListItem* item);
  30. void appendRows(const QList<ListItem*> &items);
  31. void insertRow(int row, ListItem* item);
  32. bool removeRow(int row, const QModelIndex &parent = QModelIndex());
  33. bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
  34. ListItem* takeRow(int row);
  35. bool takeRows( int row, int count, const QModelIndex &parent = QModelIndex() );
  36. ListItem* value( int row );
  37. ListItem* find(const QString &id) const;
  38. ListItem* find(const QString &id, int &row) const;
  39. QModelIndex indexFromItem( const ListItem* item) const;
  40. void clear();
  41. private slots:
  42. void handleItemChange();
  43. private:
  44. ListItem* m_prototype;
  45. QList<ListItem*> m_list;
  46. };
  47. #endif // LISTMODEL_H