treemodel.cpp

Go to the documentation of this file.
00001 #include "treeitem.h"
00002 #include "treemodel.h"
00003 #include "main.h"
00004 #include "recordtabledata.h"
00005 
00006 #include <QtGui>
00007 
00008 TreeModel::TreeModel(QObject *parent) : QAbstractItemModel(parent)
00009 {
00010  return;
00011 }
00012 
00013 TreeModel::~TreeModel(void)
00014 {
00015  return;
00016 }
00017 
00018 int TreeModel::columnCount(const QModelIndex &parent) const
00019 {
00020  Q_UNUSED(parent);
00021  
00022  // Ранее число столбцов вычислялось исходя из 
00023  // количества полей в корневом элементе
00024  // return rootItem->fieldCount();
00025  
00026  return 1;
00027 }
00028 
00029 QVariant TreeModel::data(const QModelIndex &index, int role) const
00030 {
00031     // Если индекс невалиден, возвращается несуществующий элемент
00032     if(!index.isValid())return QVariant();
00033 
00034     // Если запрашивается окраска текста элемента
00035     if(role==Qt::ForegroundRole)
00036     {
00037      TreeItem *item = getItem(index);
00038 
00039      if(item->recordtable_getrowcount()>0)
00040       return Qt::black;// Если узел содержит таблицу конечных записей
00041      else
00042       return Qt::darkGray; // Обычная ветка
00043     }
00044 
00045     // Если запрашивается содержимое текста элемента
00046     if(role==Qt::DisplayRole || role== Qt::EditRole)
00047     {
00048      TreeItem *item = getItem(index);
00049      
00050      // Запрашивается строка имени с количеством элементов
00051      return item->data("dynamicname"); 
00052     }
00053 
00054     return QVariant();
00055 }
00056 
00057 
00058 Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
00059 {
00060     if (!index.isValid())
00061         return Qt::ItemIsEnabled;
00062 
00063     return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
00064 }
00065 
00066 
00067 // Получение указателя на Item-злемент связанный с заданным QModelIndex
00068 TreeItem *TreeModel::getItem(const QModelIndex &index) const
00069 {
00070     if (index.isValid()) {
00071         TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
00072         if (item) return item;
00073     }
00074     return rootItem;
00075 }
00076 
00077 
00078 // Получение указателя на Item-злемент с указанным путем
00079 TreeItem *TreeModel::getItem(QStringList path) const
00080 {
00081  TreeItem *curritem=rootItem;
00082  
00083  // Перебор идентификаторов пути
00084  for(int i=1;i<path.size();i++)
00085  {
00086   int found=0;
00087   
00088   // Поиск нужного идентификатора в подчиненных узлах текущего узла
00089   for(int j=0;j<curritem->childCount();j++)
00090    if( (curritem->child(j))->data("id").toString() == path.at(i) )
00091     {   
00092      // Узел найден, он становится текущим
00093      curritem=curritem->child(j);
00094      found=1;
00095      break;
00096     } 
00097   
00098   // Если очередной идентификатор пути не был найден
00099   if(found==0)
00100    critical_error("Detect bad path in getItem() method "+path.join(","));
00101  }
00102 
00103  return curritem;
00104  
00105 } 
00106 
00107 
00108 // Получение заголовка столбца
00109 // Заголовки хранятся в корневом Item элементе просто в виде значений 
00110 // для каждого столбца
00111 // section - для какого столбца возвращается заголовок
00112 QVariant TreeModel::headerData(int section, Qt::Orientation orientation,
00113                                int role) const
00114 {
00115  Q_UNUSED(section);
00116  Q_UNUSED(orientation);
00117  Q_UNUSED(role);
00118   
00119  // Для всех столбцов возвращается одинаковое значение
00120  // фактически используется только один столбец
00121  return "";
00122  
00123   /*
00124    if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
00125         return rootItem->data(section);
00126 
00127     return QVariant();
00128  */
00129 }
00130 
00131 
00132 // Получение индекса элемента, который задан через parent и 
00133 // номер строки и столбца относительно parent (нумерация с нуля)
00134 // Загадочный метод, надо еще подумать что он делает на самом деле
00135 QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
00136 {
00137     if (parent.isValid() && parent.column() != 0)
00138         return QModelIndex();
00139 
00140     TreeItem *parentItem = getItem(parent);
00141 
00142     TreeItem *childItem = parentItem->child(row);
00143     if (childItem)
00144         return createIndex(row, column, childItem);
00145     else
00146         return QModelIndex();
00147 }
00148 
00149 
00150 // Вставка пустых строк с позиции position в количестве rows
00151 bool TreeModel::insertRows(int position, int rows, const QModelIndex &parent)
00152 {
00153  TreeItem *parentItem = getItem(parent);
00154  bool success;
00155 
00156  beginInsertRows(parent, position, position + rows - 1);
00157  
00158  // Добавляются строки начиная с указанной позиции, в количестве rows
00159  // с числом столбцов равным единице
00160  success = parentItem->insertChildren(position, rows, 1); 
00161  
00162  endInsertRows();
00163 
00164  return success;
00165 }
00166 
00167 
00168 QModelIndex TreeModel::parent(const QModelIndex &index) const
00169 {
00170     if (!index.isValid())
00171         return QModelIndex();
00172 
00173     TreeItem *childItem = getItem(index);
00174     TreeItem *parentItem = childItem->parent();
00175 
00176     if (parentItem == rootItem)
00177         return QModelIndex();
00178 
00179     return createIndex(parentItem->childNumber(), 0, parentItem);
00180 }
00181 
00182 
00183 bool TreeModel::removeRows(int position, int rows, const QModelIndex &parent)
00184 {
00185     TreeItem *parentItem = getItem(parent);
00186     bool success = true;
00187 
00188     beginRemoveRows(parent, position, position + rows - 1);
00189     success = parentItem->removeChildren(position, rows);
00190     endRemoveRows();
00191 
00192     return success;
00193 }
00194 
00196 int TreeModel::rowCount(const QModelIndex &parent) const
00197 {
00198     TreeItem *parentItem = getItem(parent);
00199 
00200     return parentItem->childCount();
00201 }
00202 
00203 
00204 // Установка значений в Item элементе, связанного с указанным QModelIndex 
00205 bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
00206 {
00207     if (role != Qt::EditRole) return false;
00208 
00209     // Вычисляется указатель на Item элемент по QModelIndex 
00210     // в визуальной модели дерева
00211     TreeItem *item = getItem(index);
00212 
00213     // Устанавливаются данные в Item элемент
00214     item->setData("name", value.toString());
00215     return true;
00216 }
00217 
00218 
00219 bool TreeModel::setHeaderData(int section, Qt::Orientation orientation,
00220                               const QVariant &value, int role)
00221 {
00222     if (role != Qt::EditRole || orientation != Qt::Horizontal)
00223         return false;
00224 
00225     Q_UNUSED(section);
00226     rootItem->setData("name", value.toString());
00227     return true;
00228 }

Generated on Mon Feb 2 00:25:34 2009 for mytetra by  doxygen 1.5.1