PySide:QFileSystemModel-显示/显示根项

时间:2018-11-22 12:26:00

标签: python pyside qtreeview qfilesystemmodel

我正在使用QFileSystemModel在QTreeView中显示设置的根路径的子目录。一切正常,但也很高兴看到Root项目,因为它现在已隐藏。

model = QtGui.QFileSystemModel()
model.setRootPath(path)

treeview.setModel(model)
treeview.setRootIndex(model.index(path))
treeview.show()

编辑:操作系统是Windows 7

1 个答案:

答案 0 :(得分:1)

这个想法是使用父目录作为根目录并过滤兄弟目录,为此,我创建了一个QSortFilterProxyModel来接收所需目录的索引,但是您必须将其传递给QPersistentModelIndex,因为后者是永久的,与QModelIndex不同,后者可以随时更改。

import os
from PySide import QtCore, QtGui

class FileProxyModel(QtGui.QSortFilterProxyModel):
    def setIndexPath(self, index):
        self._index_path = index
        self.invalidateFilter()

    def filterAcceptsRow(self, sourceRow, sourceParent):
        if hasattr(self, "_index_path"):
            ix = self.sourceModel().index(sourceRow, 0, sourceParent)
            if self._index_path.parent() == sourceParent and self._index_path != ix:
                return False
        return super(FileProxyModel, self).filterAcceptsRow(sourceRow, sourceParent)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    path = # ...
    parent_dir = os.path.abspath(os.path.join(path, os.pardir))
    treeview = QtGui.QTreeView()
    model = QtGui.QFileSystemModel(treeview)
    model.setRootPath(QtCore.QDir.rootPath())
    proxy = FileProxyModel(treeview)
    proxy.setSourceModel(model)
    proxy.setIndexPath(QtCore.QPersistentModelIndex(model.index(path)))
    treeview.setModel(proxy)
    treeview.setRootIndex(proxy.mapFromSource(model.index(parent_dir)))
    treeview.expandAll()
    treeview.show()
    sys.exit(app.exec_())