如何获取QTreeWidget的项目数 [英] How to get the number of items of a QTreeWidget

查看:1856
本文介绍了如何获取QTreeWidget的项目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个QTreeWidget,我试图列出所有显示的项目.

I have created a QTreeWidget, I'm trying to list all the items displayed.

如果项目有孩子但没有展开,我不想进入项目.确实获得了我在树中可以看到的项目数.

I do not want to go inside the items if the item have child but not expanded. It's really getting the number of Items I can see in the tree.

我尝试过:

   for( int i = 0; i < MyTreeWidget->topLevelItemCount(); ++i )
    {
       QTreeWidgetItem *item = MyTreeWidget->topLevelItem(i);
       ...

但这只是给我topLevelItem,我希望我能看到的全部.在该示例中,我应该能够计数14个项目

but this is giving me only the topLevelItem and I want all I can see. In the example, I should be able to count 14 items

推荐答案

您可以编写一个递归函数,该递归函数将在层次结构上运行并计算所有可见项.例如:

You can write a recursive function that will run over the hierarchy and count all visible items. For example:

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

这篇关于如何获取QTreeWidget的项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆