如何通过文件名过滤QFileSystemModel的文件列表?

时间:2019-06-17 07:56:59

标签: python pyqt5 pyside2 qfilesystemmodel

我想做一个可以显示特定文件夹的管理员。 假设我想过滤掉没有扩展名的文件夹。

enter image description here

尝试1:QFileSystemModel.setNameFilters()

... ...

# get file data
path = 'f:/tmp2'
dirModel = QtWidgets.QFileSystemModel()
dirModel.setRootPath(path)
dirModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Dirs) 

# filter folders
dirModel.setNameFilters(['*.asset']) 
# worked. but i want the opposite: that folders do not contain ".asset".

#dirModel.setNameFilters(['(^\.asset)$']) 
# regular expression is not work. nothing shows up.

# show window
... ... 

尝试2:QtCore.QSortFilterProxyModel()

... ...
# get file data
path = 'f:/tmp2'
dirModel = QtWidgets.QFileSystemModel()
dirModel.setRootPath(path)
dirModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Dirs) 

# filter folders
proxyModel = QtCore.QSortFilterProxyModel()
proxyModel.setSourceModel(dirModel)
proxyModel.setFilterRegExp("(^\.asset)$") # if no this line, all folders are displayed; add this line, nothing shows up.

# show window
... ...

我尝试修改正则表达式,但结果相同。

1 个答案:

答案 0 :(得分:2)

  1. setNameFilters()仅支持通配符,不支持正则表达式,因此会失败。

  2. 使用this answer已实现对名称没有扩展名 的文件夹的过滤。

import os
from PyQt5 import QtCore, QtGui, QtWidgets

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "56627022")
    dirModel = QtWidgets.QFileSystemModel()
    dirModel.setRootPath(QtCore.QDir.rootPath())
    dirModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Dirs)

    view1 = QtWidgets.QTreeView()
    view1.setModel(dirModel)
    view1.setRootIndex(dirModel.index(path))

    proxyModel = QtCore.QSortFilterProxyModel()
    proxyModel.setSourceModel(dirModel)
    proxyModel.setFilterRegExp(r"^([^.]+)$")

    view2 = QtWidgets.QTreeView()
    view2.setModel(proxyModel)
    view2.setRootIndex(proxyModel.mapFromSource(dirModel.index(path)))

    w = QtWidgets.QWidget()
    hlay = QtWidgets.QHBoxLayout(w)
    hlay.addWidget(view1)
    hlay.addWidget(view2)
    w.show()

    sys.exit(app.exec_())

enter image description here