Skip to main content
 首页 » 编程设计

python之PYQT 文件树的路径

2025年05月04日11xiaohuochai

我正在处理一个项目,其中我需要在 TreeView 中显示一些文件夹。我有一个完整文件路径的列表,例如:

  • C:\folder1\file1
  • C:\folder1\folder11\file2
  • C:\文件夹2\文件3

等等

好吧,文件路径实际上存储在我通过运行查询获取的 sql server 中。

我正在寻找一种将其放入 QTreeView 的方法。

我尝试过使用 QFileSystemModel 和 setNameFilters 但这不起作用,因为您无法在过滤器中输入路径。

有人建议使用 QSortFilterProxyModel,但我不知道该怎么做。

谢谢。

汤姆。

请您参考如下方法:

请看下面的示例是否适合您:

import sys 
from PyQt4 import QtGui, QtCore 
 
class TestSortFilterProxyModel(QtGui.QSortFilterProxyModel): 
    def __init__(self, parent=None): 
        super(TestSortFilterProxyModel, self).__init__(parent) 
        self.filter = ['folder0/file0', 'folder1/file1']; 
 
    def filterAcceptsRow(self, source_row, source_parent): 
        index0 = self.sourceModel().index(source_row, 0, source_parent) 
        filePath = self.sourceModel().filePath(index0)  
 
        for folder in self.filter: 
            if filePath.startsWith(folder) or QtCore.QString(folder).startsWith(filePath): 
                return True;         
        return False     
 
class MainForm(QtGui.QMainWindow): 
    def __init__(self, parent=None): 
        super(MainForm, self).__init__(parent) 
 
        model = QtGui.QFileSystemModel(self) 
        model.setRootPath(QtCore.QDir.currentPath()) 
 
        proxy = TestSortFilterProxyModel(self) 
        proxy.setSourceModel(model)      
 
        self.view = QtGui.QTreeView() 
        self.view.setModel(proxy) 
 
        self.setCentralWidget(self.view) 
 
def main(): 
    app = QtGui.QApplication(sys.argv) 
    form = MainForm() 
    form.show() 
    app.exec_() 
 
if __name__ == '__main__': 
    main() 

希望这对你有帮助,问候