我有一个使用 QTreeView 和 QFileSystemModel 的 QWidget。
我创建了一个接收路径的函数。如果它是有效路径,我希望 TreeView 将其根更新为给定路径。
到目前为止,这部分工作完美无缺。但是如果没有给出路径,我想将 TreeView 恢复到其原始状态。
这部分我无法解决。
问题是,更新 TreeView 需要什么?
我的示例代码是:
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())