pyqt5 tablewidget获取表头内容
时间: 2023-09-01 21:01:46 浏览: 865
在使用PyQt5的TableWidget获取表头内容时,可以通过`horizontalHeaderItem(columnIndex)`方法获取指定列的表头项。
以下是一个示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem
app = QApplication(sys.argv)
# 创建TableWidget实例
tableWidget = QTableWidget()
tableWidget.setColumnCount(3)
tableWidget.setRowCount(4)
# 设置表头内容
tableWidget.setHorizontalHeaderLabels(['姓名', '年龄', '性别'])
# 获取表头内容
headerLabels = []
for col in range(tableWidget.columnCount()):
header = tableWidget.horizontalHeaderItem(col)
if header is not None:
headerLabels.append(header.text())
print(headerLabels)
sys.exit(app.exec_())
```
运行以上代码,可以通过`horizontalHeaderItem()`方法获取到每个表头项的内容,并将其存储在`headerLabels`列表中。在这个示例中,输出的结果为`['姓名', '年龄', '性别']`。
该方法可以用于获取任意列的表头内容,只需要传入对应的列索引即可。注意,列索引从0开始计数。
阅读全文
相关推荐


















