首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PySide: QFileSystemModel -显示/显示根项

PySide: QFileSystemModel -显示/显示根项
EN

Stack Overflow用户
提问于 2018-11-22 12:26:00
回答 1查看 563关注 0票数 2

我使用QFileSystemModel在QTreeView中显示集合根路径的子目录。工作一切良好,但它将是非常好也看到根项目,因为它现在是隐藏的。

代码语言:javascript
复制
model = QtGui.QFileSystemModel()
model.setRootPath(path)

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

编辑:操作系统是Windows 7

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-22 17:59:03

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

代码语言:javascript
复制
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_())
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53430989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档