索引由模型提供,而不是由视图提供。该视图提供了rootIndex()
指示它认为模型中的哪个节点为根;它可能是一个无效的索引。否则与数据无关。你必须遍历模型本身 - 你可以从view->model()
.
以下是模型的深度优先演练:
void iterate(const QModelIndex & index, const QAbstractItemModel * model,
const std::function<void(const QModelIndex&, int)> & fun,
int depth = 0)
{
if (index.isValid())
fun(index, depth);
if ((index.flags() & Qt::ItemNeverHasChildren) || !model->hasChildren(index)) return;
auto rows = model->rowCount(index);
auto cols = model->columnCount(index);
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
iterate(model->index(i, j, index), model, fun, depth+1);
}
函子fun
为模型中的每个项目调用,从根开始并按深度-行-列顺序进行。
E.g.
void dumpData(QAbstractItemView * view) {
iterate(view->rootIndex(), view->model(), [](const QModelIndex & idx, int depth){
qDebug() << depth << ":" << idx.row() << "," << idx.column() << "=" << idx.data();
});
}