|
1.根据行、列及父项信息生成 QModelIndex- QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
- {
- if (parent.isValid() && parent.column() != 0)
- return QModelIndex();
- TreeItem *parentItem = getItem(parent);
- TreeItem *childItem = parentItem->child(row);
- if (childItem)
- return createIndex(row, column, childItem);
- else
- return QModelIndex();
- }
复制代码 注:QModelIndex在这起到一个数据和界面关联的作用,即开始时根据行列设置对应的项信息指针(TreeItem *childItem),供后面获取数据时获取((index.internalPointer())
2.每一个单元格数据的获取 即根据QModelIndex(内部含有行、列及父项信息)得到要显示的数据- QVariant TreeModel::data(const QModelIndex &index, int role) const
- {
- if (!index.isValid())
- return QVariant();
- if (role != Qt::DisplayRole && role != Qt::EditRole)
- return QVariant();
- TreeItem *item = getItem(index);
- return item->data(index.column());
- }
- TreeItem *TreeModel::getItem(const QModelIndex &index) const
- {
- if (index.isValid()) {
- TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
- if (item)
- return item;
- }
- return rootItem;
- }
复制代码 |
|