tableWidget遍历
在PyQt中,可以使用QTableWidget的rowCount()和columnCount()方法获取表格的行数和列数。然后可以使用双层循环遍历整个表格中的每个单元格。
以下是一个简单的示例代码:
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem
app = QApplication([])
# 创建一个3行2列的表格
tableWidget = QTableWidget(3, 2)
# 向表格中添加数据
tableWidget.setItem(0, 0, QTableWidgetItem("Cell (0, 0)"))
tableWidget.setItem(0, 1, QTableWidgetItem("Cell (0, 1)"))
tableWidget.setItem(1, 0, QTableWidgetItem("Cell (1, 0)"))
tableWidget.setItem(1, 1, QTableWidgetItem("Cell (1, 1)"))
tableWidget.setItem(2, 0, QTableWidgetItem("Cell (2, 0)"))
tableWidget.setItem(2, 1, QTableWidgetItem("Cell (2, 1)"))
# 遍历表格中的每个单元格
for row in range(tableWidget.rowCount()):
for column in range(tableWidget.columnCount()):
item = tableWidget.item(row, column)
print(f"Cell ({row}, {column}): {item.text()}")
app.exec_()
运行上述代码,将会输出以下结果:
Cell (0, 0): Cell (0, 0)
Cell (0, 1): Cell (0, 1)
Cell (1, 0): Cell (1, 0)
Cell (1, 1): Cell (1, 1)
Cell (2, 0): Cell (2, 0)
Cell (2, 1): Cell (2, 1)
这样就可以遍历QTableWidget中的每个单元格,并对其进行操作
原文地址: https://www.cveoy.top/t/topic/hRVa 著作权归作者所有。请勿转载和采集!