QTreeView calls QAbstractItemModel::hasChildren() even for invisible items

591 views Asked by At

I have a custom tree model with many items. It has more than 1000000 items at the first level below the top level. When I expand this level in a QTreeView it calls model.hasChildren() for each of these items even though the items are not visible (you would need to scroll down, down, down... to make them visible). The trouble is that my function hasChildren() takes some time especially when called million times (takes about 10 secs - in PySide/PyQt). My questions are:

1) I understand that hasChildren() is called for visible items because it must know whether the item should be expandable (if it has children) or not. But why it is called for invisible items (I mean those which are not inside the visible range and become visible only after scrolling down)? In my view it should be called only when the item is about to become visible. Am I missing somethig?

2) How to work around this issue?

1

There are 1 answers

1
Oliver On

You likely need to override fetchMore/canFetchMore per pyqt docs. Basically when you expand the root, fetchMore() will be called, you will only return a subset of data items; when the user scrolls, the view will ask the root if it can fetch more; if it answers yes, fetchMore() will get called and your model can return more items. This should cause hasChildren() to be called only on the tree items fetched.