if (!index.isValid())return QVariant();CTreeItem *item = static_cast<CTreeItem*>(index.internalPointer());...
if (role == Qt::DisplayRole || role == Qt::EditRole){ switch (index.column()) { case 0: return item->data(0).toString(); case 1: return item->data(1).toString(); case 2: return item->data(2).toString(); }}
QVariant CTreeItem::data(int column){ switch (column) { case 0: return pointer->caption(); case 1: return pointer->type(); case 2: return pointer->coord(); } return QVariant();}
rootItem = new CTreeItem(0);foreach( CObject* obj, objectList){ CTreeItem* newTreeItem = 0; newTreeItem = new CTreeItem(obj, rootItem); rootItem.appendChild(newTreeItem);}
CTreeModel::~CTreeModel(){ delete rootItem;}
connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), ui.objectList, SLOT(rowsInserted(QModelIndex, int, int)));
QModelIndex TreeModel::index(const TreeItem *item, int column) const{ if (!item || (item == rootItem)) return QModelIndex(); const TreeItem *par = item->parent(); TreeItem *itm = const_cast<TreeItem*>(item); if (!par) par = rootItem; return createIndex(par->children.lastIndexOf(itm), column, itm);}bool TreeModel::appendTopLevelItem(TreeItem *item) { beginInsertRows(index(rootItem, 0), rootItem->children.count(), rootItem->children.count()); rootItem->children.append(item); item->parentItem=rootItem; endInsertRows(); return true; }
bool StringListModel::insertRows(int position, int rows, const QModelIndex &parent) { beginInsertRows(QModelIndex(), position, position+rows-1); for (int row = 0; row < rows; ++row) { stringList.insert(position, ""); } endInsertRows(); return true; }
An example usage of QStandardItemModel to create a tree: QStandardItemModel model; QStandardItem *parentItem = model.invisibleRootItem(); for (int i = 0; i < 4; ++i) { QStandardItem *item = new QStandardItem(QString("item %0").arg(i)); parentItem->appendRow(item); parentItem = item; }
bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role){ if (!index.isValid()) return false; TreeItem *itm = itemFromIndex(index); if (itm) { itm->checked = value.toInt()!=0 ? true : false; return true; } return false;}QVariant TreeModel::data(const QModelIndex &index, int role) const{ TreeItem *item = itemFromIndex(index); if (role == Qt::CheckStateRole) return item->checked ? Qt::Checked : Qt::Unchecked; if (role == Qt::DisplayRole) return item->pointer->objectName; static QIcon folder(QPixmap("images/folder.png")); if (role == Qt::DecorationRole) return folder; return QVariant(); }