帮我写用pyqt5实现在tableWidget中数据的查找和筛选
时间: 2024-02-09 11:11:18 浏览: 134
好的,以下是针对您的问题的样例代码,可以实现在tableWidget中进行数据查找和筛选:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QTableWidgetItem, QGridLayout, QLineEdit, QLabel
import sys
class TableFilter(QWidget):
def __init__(self):
super().__init__()
# 设置窗口大小
self.setGeometry(100, 100, 500, 500)
self.setWindowTitle("Table Filter")
# 初始化表格
self.table = QTableWidget(self)
self.table.setRowCount(4)
self.table.setColumnCount(3)
self.table.setHorizontalHeaderLabels(['Name', 'Age', 'Gender'])
self.table.setItem(0, 0, QTableWidgetItem('Alice'))
self.table.setItem(1, 0, QTableWidgetItem('Bob'))
self.table.setItem(2, 0, QTableWidgetItem('Charlie'))
self.table.setItem(3, 0, QTableWidgetItem('Dave'))
self.table.setItem(0, 1, QTableWidgetItem('25'))
self.table.setItem(1, 1, QTableWidgetItem('31'))
self.table.setItem(2, 1, QTableWidgetItem('43'))
self.table.setItem(3, 1, QTableWidgetItem('19'))
self.table.setItem(0, 2, QTableWidgetItem('Female'))
self.table.setItem(1, 2, QTableWidgetItem('Male'))
self.table.setItem(2, 2, QTableWidgetItem('Male'))
self.table.setItem(3, 2, QTableWidgetItem('Male'))
# 初始化文本框和标签
self.search_label = QLabel("Search:")
self.search_textbox = QLineEdit(self)
self.filter_label = QLabel("Filter:")
self.filter_textbox = QLineEdit(self)
# 初始化布局
self.layout = QGridLayout(self)
self.layout.addWidget(self.search_label, 0, 0)
self.layout.addWidget(self.search_textbox, 0, 1)
self.layout.addWidget(self.filter_label, 1, 0)
self.layout.addWidget(self.filter_textbox, 1, 1)
self.layout.addWidget(self.table, 2, 0, 1, 2)
# 链接信号和槽
self.search_textbox.textChanged.connect(self.search_table)
self.filter_textbox.textChanged.connect(self.filter_table)
# 搜索表格
def search_table(self):
search_text = self.search_textbox.text()
for row in range(self.table.rowCount()):
for col in range(self.table.columnCount()):
item = self.table.item(row, col)
if search_text in str(item.text()):
item.setBackground(QTableWidgetItem('green'))
else:
item.setBackground(QTableWidgetItem('white'))
# 筛选表格
def filter_table(self):
filter_text = self.filter_textbox.text().lower()
for row in range(self.table.rowCount()):
row_data = [self.table.item(row, col).text().lower() for col in range(self.table.columnCount())]
if filter_text in row_data:
self.table.setRowHidden(row, False)
else:
self.table.setRowHidden(row, True)
if __name__ == "__main__":
app = QApplication(sys.argv)
table_filter = TableFilter()
table_filter.show()
sys.exit(app.exec_())
```
希望这个样例代码可以帮助您。如果您有任何问题,请随时告诉我。
阅读全文