PYQT文件路径

2024-09-27 21:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个项目,我需要在树状视图中显示一些文件夹。我有完整的文件路径列表,如:

  • C: \文件夹1\文件1
  • C: \文件夹1\文件夹11\文件2
  • C: \文件夹2\文件3

等等

文件路径实际上存储在一个sql服务器中,我通过运行一个查询来获得它。在

我在找一种方法把它放进一个QTreeView中。在

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

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

谢谢。在

汤姆。在


Tags: 文件项目方法路径服务器文件夹视图过滤器
1条回答
网友
1楼 · 发布于 2024-09-27 21:25:13

请看下面的一个例子是否对你有用:

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

希望这对你有帮助,谢谢

相关问题 更多 >

    热门问题