如何更正QTreeView上的“展开/折叠”图标?

时间:2019-09-14 06:35:32

标签: python qtreeview pyside2 qfilesystemmodel

enter image description here

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

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

QFileSystemModel ---> QTreeView

edit3:

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!

1 个答案:

答案 0 :(得分:0)

似乎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_())