我创建了一个 QTreeWidget,我正在尝试列出所有显示的项目。
如果该项目有子项但未扩展,我不想进入该项目。它确实获取了我在树中可以看到的项目数量。
我努力了 :
for( int i = 0; i < MyTreeWidget->topLevelItemCount(); ++i )
{
QTreeWidgetItem *item = MyTreeWidget->topLevelItem(i);
...
但这只给了我 topLevelItem,我想要我能看到的所有内容。在这个例子中,我应该能够数出 14 项
您可以编写一个递归函数,该函数将在层次结构上运行并计算所有可见项目的数量。例如:
int treeCount(QTreeWidget *tree, QTreeWidgetItem *parent = 0)
{
int count = 0;
if (parent == 0) {
int topCount = tree->topLevelItemCount();
for (int i = 0; i < topCount; i++) {
QTreeWidgetItem *item = tree->topLevelItem(i);
if (item->isExpanded()) {
count += treeCount(tree, item);
}
}
count += topCount;
} else {
int childCount = parent->childCount();
for (int i = 0; i < childCount; i++) {
QTreeWidgetItem *item = parent->child(i);
if (item->isExpanded()) {
count += treeCount(tree, item);
}
}
count += childCount;
}
return count;
}
以及用法:
QTreeWidget tw;
// Add items
[..]
int visibleItemsCount = treeCount(&tw);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)