PySide:QFileSystemModel - Display/Show 根项

PySide: QFileSystemModel - Display/Show Root Item

我正在使用 QFileSystemModel 在 QTreeView 中显示一组根路径的子目录。一切正常,但如果能同时看到 Root 项,因为它现在是隐藏的,那就太好了。

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

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

编辑:OS 是 Windows 7

我的想法是将父目录用作根目录并过滤同级目录,为此我创建了一个 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_())