QTreeView with QAbstractItemModel collapses root node when selecting anything for the first time
-
In PyQt5, I have a
QTreeView
with a custom class extendingQAbstractItemModel
. I have a problem I can't seem to solve, or find the root cause, where only on the first time I select any node, the entireQTreeView
collapses. When I expand the root node after, it no longer has that problem for the succeeding selections.At the beginning, my nodes have no children. I'm fetching the data / children from the server only if the node is expanded (using
QAbstractItemView.expanded
signal). I overridedQAbstractItemModel.insertRow
and I call the recommended functionsbeginInsertRows
andendInsertRows
before and after I update the model data. I also emit thelayoutToBeChanged
andlayoutChanged
signals.I can't seem to figure out what causes that selection issue.
This is my code for fetching data for nodes that are expanded:
class FileTree(QTreeView): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Class for fetching data from server self.folders = Folders() self.setup_ui() self.populate() self.notify = NotificationDialog() def populate(self): ret, root_folders = self.folders.root() if ret: self.tree_model = TreeModel(root_folders) self.setModel(self.tree_model) def populate_folder_node(self, node, index): ret, children = self.folders.children(node.data['folder_id']) if ret: self.tree_model.removeRows(0, len(node.children), index) # Update view via model signal (Source: https://stackoverflow.com/a/51587327/5575610) self.tree_model.layoutAboutToBeChanged.emit() for i, data in enumerate(children): self.tree_model.insertRow(Node(data), i, index) self.tree_model.layoutChanged.emit() def on_node_expanded(self, index: QModelIndex): if not index.isValid(): return node = index.internalPointer() node.opened = True self.populate_folder_node(node, index)