[英]How to loop over QAbstractItemView indexes?
I want to fire QAbstractItemView::doubleClicked
slot programaticaly for an item that has specific text. 我想针对具有特定文本的项目触发QAbstractItemView::doubleClicked
slot programaticaly。 I want to do this using QAbstractItemView
class and not it's implementations if possible. 我想使用QAbstractItemView
类来做这个,如果可能的话,不是它的实现。
This task boils down to looping over items and comparing strings. 此任务归结为循环项目和比较字符串。 But I cannot find any method that would give me all QModelIndex
es. 但我找不到任何能给我所有QModelIndex
es的方法。 The only method that gives any QModelIndex
without parameters is QAbstractItemView::rootIndex
. 给出任何没有参数的QModelIndex
的唯一方法是QAbstractItemView::rootIndex
。 But when I look into QModelIndex
docs, I again cannot see a way to access it's children and siblings. 但是当我查看QModelIndex
文档时,我再次看不到访问它的孩子和兄弟姐妹的方法。
So how to access all QModelIndex
es in QAbstractItemView
? 那么如何在QAbstractItemView
访问所有QModelIndex
?
The indexes are provided by the model, not by the view. 索引由模型提供,而不是由视图提供。 The view provides the rootIndex()
to indicate what node in the model it considers as root; 视图提供了rootIndex()
来指示模型中它认为是root的节点; it might be an invalid index. 它可能是一个无效的索引。 Otherwise it has nothing to do with the data. 否则它与数据无关。 You have to traverse the model itself - you can get it from view->model()
. 您必须遍历模型本身 - 您可以从view->model()
获取它。
Here's a depth-first walk through a 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 (!model->hasChildren(index) || (index.flags() & Qt::ItemNeverHasChildren)) 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);
}
The functor fun
gets invoked for every item in the model, starting at root and going in depth-row-column order. 为模型中的每个项调用functor fun
,从root开始并按深度 - 行 - 列顺序进行调用。
Eg 例如
void dumpData(QAbstractItemView * view) {
iterate(view->rootIndex(), view->model(), [](const QModelIndex & idx, int depth){
qDebug() << depth << ":" << idx.row() << "," << idx.column() << "=" << idx.data();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.