通过QSortFilterProxyModel的setFilterRegExp方法,设置指定的正则表达式
"""
********************************************************************************************
@作者: Aaron.Ma
@文件: view.py
@时间: 2022/8/15 16:12
********************************************************************************************
"""
import sys
import typing
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class _SortFilterProxyModel(QtCore.QSortFilterProxyModel):
def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = ...) -> typing.Any:
if orientation == QtCore.Qt.Horizontal:
if role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignCenter
return super(_SortFilterProxyModel, self).headerData(section, orientation, role)
class App(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)
self.resize(640, 480)
self.setWindowTitle("Dir View")
self.fileSystemModel = QtWidgets.QFileSystemModel()
self.fileSystemModel.setRootPath(QDir.currentPath())
self.fileSystemModel.setNameFilters(['*'])
self.fileSystemModel.setFilter(QDir.Files | QDir.NoDotAndDotDot | QDir.NoSymLinks)
self.fileSystemModel.setNameFilterDisables(False)
self.proxyModel = _SortFilterProxyModel()
self.proxyModel.setFilterRegExp(QRegExp("^([^.]+)$", Qt.CaseInsensitive))
self.proxyModel.setSourceModel(self.fileSystemModel)
self.setModel(self.proxyModel)
sourceIndex = self.fileSystemModel.index(QDir.currentPath())
self.setRootIndex(self.proxyModel.mapFromSource(sourceIndex))
self.doubleClicked.connect(self.tree_cilcked)
self.setIndentation(10)
def tree_cilcked(self, index):
print(self.fileSystemModel.fileName(index))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())