custommodel.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #ifndef CUSTOMMODEL_H
  2. #define CUSTOMMODEL_H
  3. #include "QtWidgets/qtreeview.h"
  4. #include <QAbstractItemModel>
  5. #include <QMouseEvent>>
  6. struct ListItem
  7. {
  8. QString text; // 用于显示的文本
  9. QList<ListItem> children; // 子项列表
  10. bool operator==(const ListItem& other) const
  11. {
  12. return text == other.text && children == other.children;
  13. }
  14. };
  15. class CustomModel : public QAbstractItemModel
  16. {
  17. Q_OBJECT
  18. public:
  19. explicit CustomModel(QObject* parent = nullptr);
  20. ~CustomModel();
  21. // 重写必要的函数
  22. QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
  23. QModelIndex parent(const QModelIndex& child) const override;
  24. int rowCount(const QModelIndex& parent = QModelIndex()) const override;
  25. int columnCount(const QModelIndex& parent = QModelIndex()) const override;
  26. QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
  27. Qt::ItemFlags flags(const QModelIndex& index) const override;
  28. bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
  29. bool insertTopLevelItem(int row, const ListItem& item);
  30. bool insertChildItem(const QModelIndex& parent, int row, const ListItem& item);
  31. bool removeTopLevelItem(int row);
  32. bool removeChildItem(const QModelIndex& parent, int row);
  33. ListItem getItem(const QModelIndex& index) const;
  34. private:
  35. // 自定义数据结构用于存储一级列表和二级列表的数据
  36. QList<ListItem> topLevelItems;
  37. };
  38. #endif // CUSTOMMODEL_H