QTableWidget中包含id name score信息,按照id,将所有信息按id升序进行排序
时间: 2023-11-26 08:04:22 浏览: 119
可以使用QTableWidget的sortItems()方法来实现按照id升序排序。具体步骤如下:
1. 获取id列的索引值,可以使用QTableWidget的horizontalHeaderItem()方法获取列头控件,再使用QHeaderView的visualIndex()方法获取列的视觉索引值。
```
header = tableWidget.horizontalHeaderItem(0) # 获取第一列的列头控件
id_column = header.visualIndex() # 获取第一列的视觉索引值
```
2. 调用sortItems()方法进行排序,设置排序方式为升序(Qt.AscendingOrder)。
```
tableWidget.sortItems(id_column, Qt.AscendingOrder)
```
完整代码如下:
```
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QHeaderView
from PyQt5.QtCore import Qt
app = QApplication([])
# 创建表格
tableWidget = QTableWidget()
tableWidget.setColumnCount(3)
tableWidget.setHorizontalHeaderLabels(['id', 'name', 'score'])
# 添加数据
data = [
{'id': '1001', 'name': '张三', 'score': '90'},
{'id': '1003', 'name': '李四', 'score': '85'},
{'id': '1002', 'name': '王五', 'score': '95'},
]
for i, row_data in enumerate(data):
for j, value in enumerate(row_data.values()):
tableWidget.setItem(i, j, QTableWidgetItem(value))
# 按照id升序排序
header = tableWidget.horizontalHeaderItem(0) # 获取第一列的列头控件
id_column = header.visualIndex() # 获取第一列的视觉索引值
tableWidget.sortItems(id_column, Qt.AscendingOrder)
tableWidget.show()
app.exec_()
```
阅读全文
相关推荐
















