【问题标题】:How to correct the "expand/collapse" icon on the QTreeView?如何更正 QTreeView 上的“展开/折叠”图标?
【发布时间】:2020-01-15 21:18:26
【问题描述】:

当你看到这个展开图标时,你会认为文件夹下有东西。但什么都没有。此问题会导致用户体验不佳。如何解决? (**如果文件夹为空,则不显示展开图标。)

我的代码基本上是这样的:

QFileSystemModel ---> QTreeView

编辑3:

import sys
from PySide2.QtCore import *
from PySide2.QtWidgets import *

libPath = 'f:/tmp22'

# RUN ------------------------------------------------------------------
if __name__ == '__main__':
    app = QApplication(sys.argv)

    # data model ----------------------------------------------------------
    treeModel = QFileSystemModel()
    treeModel.setFilter(QDir.NoDotAndDotDot | QDir.Dirs)
    treeModel.setRootPath(libPath)

    # setup ui -------------------------------------------------------------
    treeView = QTreeView()
    treeView.setModel(treeModel)
    treeView.setRootIndex(treeModel.index(libPath))

    # show ui -------------------------------------------------------------
    treeView.show()
    sys.exit(app.exec_())

文件夹的结构:

F:/tmp22
F:/tmp22/folder1    <-------- empty!
F:/tmp22/_folder2   <-------- empty!

【问题讨论】:

    标签: python qtreeview pyside2 qfilesystemmodel


    【解决方案1】:

    QFileSystemModel 似乎认为一个文件夹总是有子文件夹,因此 hasChildren() 在这种情况下返回 True。要纠正这个问题,如果文件夹不符合过滤条件,则必须通过返回 false 来覆盖此方法。

    import sys
    
    # PySide2
    from PySide2.QtCore import QDir, QSortFilterProxyModel
    from PySide2.QtWidgets import QApplication, QFileSystemModel, QTreeView
    
    
    libPath = 'f:/tmp22'
    
    
    class FileSystemModel(QFileSystemModel):
        def hasChildren(self, parent):
            file_info = self.fileInfo(parent)
            _dir = QDir(file_info.absoluteFilePath())
            return bool(_dir.entryList(self.filter()))
    
    # RUN ------------------------------------------------------------------
    if __name__ == "__main__":
        app = QApplication(sys.argv)
    
        # data model ----------------------------------------------------------
        treeModel = FileSystemModel()
        treeModel.setFilter(QDir.NoDotAndDotDot | QDir.Dirs)
        treeModel.setRootPath(libPath)
    
        # setup ui -------------------------------------------------------------
        treeView = QTreeView()
        treeView.setModel(treeModel)
        treeView.setRootIndex(treeModel.index(libPath))
    
        # show ui -------------------------------------------------------------
        treeView.show()
        sys.exit(app.exec_())
    

    【讨论】:

    • 如果我使用 QSortFilterProxyModel 过滤 QFileSystemModel,我是否覆盖 QFileSystemModel 或 QSortFilterProxyModel 上的 hasChildren()?
    • 我重写了 QSortFilterProxyModel.hasChildren(),它可以工作。谢谢!
    猜你喜欢
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 2015-05-31
    • 2013-10-28
    • 2011-05-05
    • 1970-01-01
    • 2018-06-14
    相关资源
    最近更新 更多