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())