c++ - Qt TreeView获取总行数,考虑的展开和折叠文件夹
问题描述
我正在处理一个 Qt 应用程序,我想在其中检索目录/文件系统模型树中可导航行的总数。这意味着如果一个文件夹被展开,它的计数会被添加,如果一个文件夹被折叠,它的计数不会被添加。作为一个整体,我希望能够检索展开和可用的每一行的数量。据我所知,没有这样的实现很容易在网上找到。两种尚未奏效的解决方案:
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())
但是,这不包括未展开的孩子等等。我希望我的问题很清楚。任何帮助表示赞赏。如果需要,我愿意提供更多信息。谢谢。
解决方案
如果每个索引都已扩展,您可以检查您的视图。那么这只是一个遍历模型的问题。
Kuba Order 的信用: 如何遍历 QAbstractItemView 索引?
基于他很好的遍历功能:
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 示例上对其进行了快速测试,它似乎有效。
推荐阅读
- c++ - 改进来自 InterlockedCompareExchange() 的原子读取
- c# - 使用单元格内容从datagridview添加到另一个datagridview单击c#
- django - 谁能告诉我如何防止在 Django 模型中存储多个输入的空白输入字段
- python - 无法使用 anaconda 安装 GCC
- sql - Postgresql:从数字开始提取文本
- amazon-web-services - 如何在 Java Application Server 或 Tomcat 上部署 KinesisAutoscaling.war?
- angular - 角度表单验证:比较不同表单组中的两个字段
- node.js - 如何在 Twilio 函数中使用 Node.js 检索 Twilio 传真 PDF 并将其附加到电子邮件中?
- mongodb - 使用不同的键重新组合数组
- powershell - 从 AD 和事件查看器匹配 SID