【问题标题】:PySide: QFileSystemModel - Display/Show Root ItemPySide:QFileSystemModel - 显示/显示根项目
【发布时间】:2018-11-23 01:59:16
【问题描述】:

我正在使用 QFileSystemModel 在 QTreeView 中显示设置根路径的子目录。一切正常,但如果 R​​oot 项目现在处于隐藏状态,那就太好了。

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

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

编辑:操作系统是 Windows 7

【问题讨论】:

  • 我还不能测试它...我会尽快告诉你 ;) (等待我的 IDE - 它在星期五搞砸了一些事情^^)
  • 似乎工作得很好。非常喜欢!
  • 啊……遗憾的是,如果根路径没有父路径,它就不起作用

标签: python pyside qtreeview qfilesystemmodel


【解决方案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_())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 2018-12-19
    • 2021-01-02
    相关资源
    最近更新 更多