treemodel.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include "treemodel.h"
  2. #include "node.h"
  3. #include <QString>
  4. #include <QColor>
  5. TreeModel::TreeModel(QObject *parent)
  6. : QAbstractItemModel(parent)
  7. {
  8. _rootItem = new QObject(this);
  9. }
  10. //QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
  11. //{
  12. // // FIXME: Implement me!
  13. //}
  14. QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
  15. {
  16. if(!hasIndex(row,column,parent))
  17. {return QModelIndex();}
  18. QObject* parentObj = objByIndex(parent);
  19. return createIndex(row,column,parentObj->children().at(row));
  20. }
  21. QModelIndex TreeModel::parent(const QModelIndex &index) const
  22. {
  23. QObject* childObj = objByIndex(index);
  24. QObject* parentObj = childObj->parent();
  25. if(parentObj ==_rootItem)
  26. {return QModelIndex();}
  27. QObject* grandParentObj = parentObj->parent();
  28. int row = grandParentObj->children().indexOf(parentObj);
  29. return createIndex(row, 0, parentObj);
  30. }
  31. int TreeModel::rowCount(const QModelIndex &parent) const
  32. {
  33. // if (!parent.isValid())
  34. // return 0;
  35. return objByIndex(parent)->children().count();
  36. }
  37. int TreeModel::columnCount(const QModelIndex &parent) const
  38. {
  39. // if (!parent.isValid())
  40. // return 0;
  41. Q_UNUSED(parent);
  42. return m_columns.count();
  43. }
  44. QVariant TreeModel::data(const QModelIndex &index, int role) const
  45. {
  46. if (!index.isValid())
  47. return QVariant();
  48. if(role == Qt::DisplayRole)
  49. {
  50. return objByIndex(index)->property(m_columns.at(index.column()).toUtf8());
  51. }
  52. if (role == Qt::ForegroundRole )
  53. {
  54. if ( static_cast<Node*>(objByIndex(index))->status() )
  55. {
  56. return QVariant( QColor( Qt::black ) );
  57. }
  58. return QVariant( QColor( Qt::gray ) );
  59. }
  60. return QVariant();
  61. }
  62. void TreeModel::AddItem(QObject *item, const QModelIndex &parentIndex)
  63. {
  64. beginInsertRows(parentIndex,rowCount(parentIndex),rowCount(parentIndex));
  65. item->setParent(objByIndex(parentIndex));
  66. endInsertRows();
  67. }
  68. QObject *TreeModel::objByIndex(const QModelIndex &index) const
  69. {
  70. if(!index.isValid())
  71. return _rootItem;
  72. return static_cast<QObject*>(index.internalPointer());
  73. }
  74. QModelIndex TreeModel::IndexById(QString id) const
  75. {
  76. QModelIndex ind = this->match(this->index(0,1),Qt::DisplayRole,QVariant(id), -1).first();
  77. return ind;
  78. }