Search code examples
python-3.xtreeviewpyqt5qfilesystemmodel

Change Root Path of Model during runtime - PyQt5


I have a QWidget where I use QTreeView und QFileSystemModel.

I created a function which receives a path. If it is a valid path I expect the TreeView to update its root to the given path.

This part works so far flawlessly. But if there is no path given, I want to revert the TreeView to its original state.

This part I cannot manage to solve.

The question is, what is necessary to update TreeView?

My example code is:

import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc


class FolderView(qtw.QWidget):
    def __init__(self):
        super().__init__()
        self.init_me()

    def init_me(self):
        self.model = qtw.QFileSystemModel()
        home_location = qtc.QStandardPaths.standardLocations(qtc.QStandardPaths.HomeLocation)[0]
        self.index = self.model.setRootPath(home_location)

        self.tree = qtw.QTreeView()
        self.tree.setModel(self.model)
        self.tree.setCurrentIndex(self.index)

        self.tree.setAnimated(False)
        self.tree.setIndentation(20)

        self.tree.setSortingEnabled(True)

        window_layout = qtw.QVBoxLayout()
        window_layout.addWidget(self.tree)

        self.setLayout(window_layout)

        self.show()            

    def set_root(self, path):
        if len(path) == 0:

        ## RETURN BACK TO NORMAL ##
            self.model.setRootPath(path)
            self.tree.setCurrentIndex(self.index)

        else:
        ## ONLY SHOW DATA FROM THE GIVEN PATH ##
            self.tree.setRootIndex(self.model.index(path))

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    mw = FolderView()
    sys.exit(app.exec())

Solution

  • When you open a model, the default rootIndex() is an invalid index.

    By using setRootIndex you are actually telling the tree to use another (possibly valid) index of the model as its root.

    To revert back to the original form, you'll have to set the root to the actual root of the model, which can be obtained by creating a new instance of QModelIndex():

    Creates a new empty model index. This type of model index is used to indicate that the position in the model is invalid.

    So, the solution is to do the following:

        self.tree.setRootIndex(qtc.QModelIndex())