0

I found this question and this question.

I've also searched elsewhere.

The situation is that (starting with all root item children collapsed) my code iterates through the tree expanding the parents of those items whose data matches a certain criterion.

I just want to find the total number of showing rows displayed in the QTreeView at the end of that process. NB I use the word "showing" rather than "visible" as this is not a question about viewports: I want the total number showing assuming a viewport large enough not to have to create a vertical scrollbar.

Is there really no simple way to achieve this? Counting the total children displayed by, for example, counting all children of all parents which are expanded in this manner, as they get expanded, would be quite complex: sometimes, for example, two siblings meet the criterion, so the first expands its parent, but the second obviously doesn't. Not only that, but a node located deep in the tree expands not only its own parent, but (if necessary) its grandparent, great-grandparent, etc.

In view of the complexity of the foregoing, another possibility would be to iterate through the tree again, after expanding, in order to count the rows displayed. This seems a ludicrous effort just to get such a simple piece of information.

Please note that I'm talking about QTreeViews, not QTableViews. With the latter it appears that it possible to use table_view.verticalHeader().count(). But a QTreeView doesn't have the method verticalHeader.

mike rodent
  • 14,126
  • 11
  • 103
  • 157
  • The solution is already given in [one of the answers](https://stackoverflow.com/a/22389583/984421) to the second question you linked to. The only difference is that the starting index should simply be first one available: i.e. `tree.model().index(0, 0, tree.rootIndex())`. – ekhumoro May 11 '22 at 17:24
  • You're right. I had spotted that but didn't examine it very closely because, as is pointed out in a comment, starting with `tv.rect()` has a few problems. But I should have looked more closely. Musicamante's version is clearer. – mike rodent May 11 '22 at 18:08

1 Answers1

2

QTreeView provides the indexAbove() and indexBelow() functions, and the latter:

Returns the model index of the item below index.

    def count_showing_rows(self):
        count = 0
        index = self.model().index(0, 0)
        while index.isValid():
            count += 1
            index = self.indexBelow(index)
        return count
musicamante
  • 41,230
  • 6
  • 33
  • 58