gpt4 book ai didi

python - 如何为 QTableWidget 创建过滤器?

转载 作者:太空宇宙 更新时间:2023-11-03 13:14:28 25 4
gpt4 key购买 nike

我正在尝试在 PySide 中使用 QLineEditQTableWidget 创建一个过滤器。我看过一些针对 C++ 使用 QSortFilterProxyModel 的教程,但不明白如何在 Python 中执行此操作。

enter image description here

我需要在“VALUE”列中搜索。

最佳答案

A QSortFilterProxyModel是代理模型,这意味着您将它放在完整的数据模型和 View 之间。 titusjan的评论很好,您可以在本地 PySide/PyQt 安装中查找 basicsortfiltermodel.py获取 Python 示例。

另外,不要使用 QTableWidget一个QTableView就足够了——你不需要 QTableWidget 的内置模型无论如何。

QTableWidget:Details

The QTableWidget class provides an item-based table view with a default model.

Table widgets provide standard table display facilities for applications. The items in a QTableWidget are provided by QTableWidgetItem.

If you want a table that uses your own data model you should use QTableView rather than this class.

我编写了一个非常简单的示例,演示了对 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 的输入作为过滤表达式。 QSortFilterProxyModelQTableView 用作模型.

它看起来像:

No filtering

Filtering

关于python - 如何为 QTableWidget 创建过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34252413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com