我编写的这段代码未能为QTreeView创建过滤器功能,请帮助我如何在TreeView中添加过滤器,如下图所示。
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
#from PyQt5.QtWidgets import QApplication, QFileSystemModel, QTreeView, QWidget, QVBoxLayout,QPushButton, QMessageBox,QDialog,QTableWidget,QTabWidget
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.treeWidget_2.setObjectName("treeWidget_2")
#self.treeWidget_2.headerItem().setText(0, "1")
self.gridLayout_2.addWidget(self.treeWidget_2, 1, 0, 1, 1)
self.model = QtWidgets.QFileSystemModel()
#self.model.setFilter(QtCore.QDir.Files)
self.model.setRootPath('')
self.treeWidget_2.setModel(self.model)
#m = self.treeWidget_2.selectionModel()
#m.selectionChanged.connect(self.onSelectionChanged)
self.treeWidget_2.setAnimated(True)
#self.treeWidget_2.setAlternatingRowColors(True)
self.treeWidget_2.setIndentation(25)
self.treeWidget_2.setSortingEnabled(True)
self.treeWidget_2.setWindowTitle("Dir View")
self.lineEdit = QtWidgets.QLineEdit(self.dockWidgetContents_5)
self.lineEdit.setObjectName("lineEdit")
self.gridLayout_2.addWidget(self.lineEdit, 0, 0, 1, 1)
#------------------
self.model = QtGui.QStandardItemModel(self.treeWidget_2)
self.proxyModel = QtCore.QSortFilterProxyModel(self.treeWidget_2)
self.proxyModel.setSourceModel(self.model)
self.treeWidget_2.setSortingEnabled(True)
# set model
self.treeWidget_2.setModel(self.proxyModel)
#self.treeWidget_2.clicked.connect(self.update_model)
self.lineEdit.textChanged.connect(self.onTextChanged)
#@QtCore.pyqtSlot(str)
def onTextChanged(self, text):
self.proxyModel.setFilterRegExp(text)