Important: Please read the Qt Code of Conduct -

QTreeView with QAbstractItemModel collapses root node when selecting anything for the first time

  • In PyQt5, I have a QTreeView with a custom class extending QAbstractItemModel. 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 entire QTreeView 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 overrided QAbstractItemModel.insertRow and I call the recommended functions beginInsertRows and endInsertRows before and after I update the model data. I also emit the layoutToBeChanged and layoutChanged 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.notify = NotificationDialog()
        def populate(self):
            ret, root_folders = self.folders.root()
            if ret:
                self.tree_model = TreeModel(root_folders)
        def populate_folder_node(self, node, index):
            ret, children = self.folders.children(['folder_id'])
            if ret:
                self.tree_model.removeRows(0, len(node.children), index)
                # Update view via model signal (Source:
                for i, data in enumerate(children):
                    self.tree_model.insertRow(Node(data), i, index)
        def on_node_expanded(self, index: QModelIndex):
            if not index.isValid():
            node = index.internalPointer()
            node.opened = True
            self.populate_folder_node(node, index)

  • Resolved: It was a bug in my code

Log in to reply