Qt TreeView获取的总行数,已展开和折叠的文件夹

时间:2018-05-16 10:16:55

标签: c++ qt qtreeview qabstractitemmodel

我正在处理一个Qt应用程序,我想在其中检索Directory / Filesystem模型树中可导航行的总数。这意味着如果文件夹被展开,则会添加其计数,如果折叠文件夹,则不会添加其计数。总的来说,我希望能够检索扩展和可用的每一行的数量。据我所知,没有这样的实现很容易在网上找到。到目前为止,有两个非工作解决方案:

int MainWindow::countRowsOfIndex_treeview( const QModelIndex & index )
{
    int count = 0;
    const QAbstractItemModel* model = index.model();
    int rowCount = model->rowCount(index);
    count += rowCount;
    for( int r = 0; r < rowCount; ++r )
        count += countRowsOfIndex_treeview( model->index(r,0,index) );
    return count;
}

这与我想要达到的目标相差甚远,因为它没有考虑未展开的文件夹。

到目前为止,我一直在使用以下方法处理单级行计数:

ui->treeView->model()->rowCount(ui->treeView->currentIndex().parent())

但是,这不计算未扩展的孩子等等。我希望我的问题很明确。任何帮助表示赞赏。如果需要,我愿意提供更多信息。感谢。

1 个答案:

答案 0 :(得分:1)

如果每个索引都被扩展,您可以检查您的视图。那么这只是遍历模型的问题。

库巴订单信用: How to loop over QAbstractItemView indexes?

基于他良好的遍历功能:

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)) 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);
}

,您可以轻松地写下您的需求:

int countExpandedNode(QTreeView * view) {
    int totalExpanded = 0;
    iterate(view->rootIndex(), view->model(), [&totalExpanded,view](const QModelIndex & idx, int depth){
        if (view->isExpanded(idx))
            totalExpanded++;
    });
    return totalExpanded;
}

调用代码:

QTreeView view;
view.setModel(&model);
view.setWindowTitle(QObject::tr("Simple Tree Model"));

view.expandAll();
view.show();


qDebug() << "total expanded" << countExpandedNode(&view);

我已经在Qt TreeModel示例上快速测试了它,它似乎有效。