栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在树形视图中显示父目录?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在树形视图中显示父目录?

QTreeView的rootIndex被隐藏,因此未显示。一种可能的解决方案是传递路径的父级,并使用QSortFilterProxyModel隐藏其他目录和文件。

import osfrom PyQt5.QtCore import pyqtSlot, QDir, QModelIndex, QSize, QSortFilterProxyModelfrom PyQt5.QtWidgets import QApplication, QFileSystemModel, QMainWindow, QTreeViewclass ProxyModel(QSortFilterProxyModel):    def __init__(self, parent=None):        super().__init__(parent)        self._root_path = ""    def filterAcceptsRow(self, source_row, source_parent):        source_model = self.sourceModel()        if self._root_path and isinstance(source_model, QFileSystemModel): root_index = source_model.index(self._root_path).parent() if root_index == source_parent:     index = source_model.index(source_row, 0, source_parent)     return index.data(QFileSystemModel.FilePathRole) == self._root_path        return True    @property    def root_path(self):        return self._root_path    @root_path.setter    def root_path(self, p):        self._root_path = p        self.invalidateFilter()class MainWindow(QMainWindow):    def __init__(self, parent=None):        super().__init__(parent)        self.create_treeview()        self.setCentralWidget(self.treeView)    def create_treeview(self):        path = "/home/data/test"        self.treeView = QTreeView()        self.treeView.setMinimumSize(QSize(250, 0))        self.treeView.setMaximumSize(QSize(250, 16777215))        self.treeView.setObjectName("treeView")        self.dirModel = QFileSystemModel()        self.dirModel.setRootPath(QDir.rootPath())        self.dirModel.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)        root_index = self.dirModel.index(path).parent()        self.proxy = ProxyModel(self.dirModel)        self.proxy.setSourceModel(self.dirModel)        self.proxy.root_path = path        self.treeView.setModel(self.proxy)        proxy_root_index = self.proxy.mapFromSource(root_index)        self.treeView.setRootIndex(proxy_root_index)        self.treeView.setHeaderHidden(True)        self.treeView.clicked.connect(self.tree_click)    @pyqtSlot(QModelIndex)    def tree_click(self, index):        ix = self.proxy.mapToSource(index)        print( ix.data(QFileSystemModel.FilePathRole), ix.data(QFileSystemModel.FileNameRole),        )if __name__ == "__main__":    import sys    app = QApplication(sys.argv)    w = MainWindow()    w.show()    sys.exit(app.exec_())


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645293.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号