You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5中QFileSystemModel的setRootPath未按预期生效求助

Fixing QFileSystemModel's setRootPath Not Working as Expected in PyQt5

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 the QModelIndex for the directory you specified—we capture that value in root_index.
  • Calling self.setRootIndex(root_index) forces the QTreeView to only display the contents of C:\ (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 import from PyQt5.QtCore import QDir)
  • Filter specific file types: model.setNameFilters(["*.txt", "*.py"]) to only show text and Python files

内容的提问来源于stack exchange,提问作者Jakob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:38:54