QSortFilterProxyModel 是代理模型,这意味着您将它放在完整的数据模型和视图之间。 titusjan 的评论很好,您可以在本地 PySide/PyQt 安装中查找 basicsortfiltermodel.py 以获取 Python 示例。
另外,除了使用QTableWidget 之外,QTableView 就足够了 - 无论如何您都不需要 QTableWidget 的内置模型。
QTableWidget:Details
QTableWidget 类提供了一个带有默认模型的基于项目的表格视图。
表格小部件为应用程序提供标准表格显示工具。 QTableWidget 中的项目由 QTableWidgetItem 提供。
如果你想要一个使用你自己的数据模型的表,你应该使用 QTableView 而不是这个类。
我编写了一个非常简单的示例,展示了对QTableView 的第三列的过滤:
from PySide import QtCore, QtGui
app = QtGui.QApplication([])
window = QtGui.QWidget()
# standard item model
model = QtGui.QStandardItemModel(5, 3)
model.setHorizontalHeaderLabels(['ID', 'DATE', 'VALUE'])
for row, text in enumerate(['Cell', 'Fish', 'Apple', 'Ananas', 'Mango']):
item = QtGui.QStandardItem(text)
model.setItem(row, 2, item)
# filter proxy model
filter_proxy_model = QtGui.QSortFilterProxyModel()
filter_proxy_model.setSourceModel(model)
filter_proxy_model.setFilterKeyColumn(2) # third column
# line edit for filtering
layout = QtGui.QVBoxLayout(window)
line_edit = QtGui.QLineEdit()
line_edit.textChanged.connect(filter_proxy_model.setFilterRegExp)
layout.addWidget(line_edit)
# table view
table = QtGui.QTableView()
table.setModel(filter_proxy_model)
layout.addWidget(table)
window.show()
app.exec_()
您有一个QStandardItemModel,它被设置为QSortFilterProxyModel 的源,它使用第三列进行过滤,并使用QLineEdit 的输入作为过滤表达式。 QSortFilterProxyModel 被 QTableView 用作模型。
它看起来像: