本文介绍了如何为QTableWidget创建过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PySide中为QTableWidgetQLineEdit创建一个过滤器.我看过一些使用QSortFilterProxyModel for C ++的教程,但是不明白如何在Python中做到这一点.

I'm trying to create a filter for QTableWidget with QLineEdit in PySide. I've seen some tutorials using QSortFilterProxyModel for C++ but couldn't understood how to do it in Python.

我需要在"VALUE"列中进行搜索.

I need to search in 'VALUE' column.

推荐答案

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

A QSortFilterProxyModel is a proxy model, that means that you put it between the your complete data model and a view. The comment by titusjan is good, you can look in your local PySide/PyQt installation for basicsortfiltermodel.py to get an example in Python.

此外,代替使用QTableWidget还是QTableView就足够了-您仍然不需要QTableWidget的内置模型.

Also, instead of using a QTableWidget a QTableView is sufficient - you won't need the inbuilt model of QTableWidget anyway.

QTableWidget:详细信息

表小部件为应用程序提供了标准的表显示功能. QTableWidgetItem中提供了QTableWidget中的项目.

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

如果要使用自己的数据模型的表,则应使用QTableView而不是此类.

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

我编写了一个非常简单的示例,展示了对QTableView的第三列的过滤:

I compiled an very simple example demonstrating filtering for the third column of a 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的源,该QSortFilterProxyModel使用第三列进行过滤,并使用QLineEdit的输入作为过滤表达式. QSortFilterProxyModel用作QTableView的模型.

You have a QStandardItemModel which is set as source of a QSortFilterProxyModel which uses the third column for filtering and uses the input of a QLineEdit as filtering expression. The QSortFilterProxyModel is used as model by a QTableView.

它看起来像:

这篇关于如何为QTableWidget创建过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 15:02