PyQt5中QFileSystemModel的setRootPath未按预期生效求助
Hey there! I ran into this exact same issue when I first started working with QFileSystemModel and QTreeView—let me break down what's going wrong and how to fix it.
The core problem here is that setRootPath() only configures the QFileSystemModel to monitor your target directory as its data source, but it doesn't automatically tell the QTreeView to use that directory as its display root. By default, QTreeView will show the model's top-level system root (like "This PC" on Windows, or the root filesystem on Linux), which is why you're not seeing just the C:\ directory as you expected.
Here's your updated code with the fix:
from PyQt5.QtWidgets import QTreeView, QFileSystemModel, QApplication class Main(QTreeView): def __init__(self): QTreeView.__init__(self) model = QFileSystemModel() # Set the root path and capture its corresponding model index root_index = model.setRootPath('C:\\') self.setModel(model) # This line is the key—tell the tree view to use this index as its display root self.setRootIndex(root_index) self.doubleClicked.connect(self.test) def test(self, signal): file_path = self.model().filePath(signal) print(file_path) if __name__ == '__main__': import sys app = QApplication(sys.argv) w = Main() w.show() sys.exit(app.exec_())
Quick breakdown of the fix:
model.setRootPath()actually returns theQModelIndexfor the directory you specified—we capture that value inroot_index.- Calling
self.setRootIndex(root_index)forces the QTreeView to only display the contents ofC:\(and its subdirectories) as the top-level of the tree, instead of showing the entire system hierarchy.
As a bonus tip, if you want to refine the model's behavior, you can add things like:
- Hide hidden files and parent directory markers:
model.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs | QDir.Files)(just remember to importfrom PyQt5.QtCore import QDir) - Filter specific file types:
model.setNameFilters(["*.txt", "*.py"])to only show text and Python files
内容的提问来源于stack exchange,提问作者Jakob

