pyqt5tablewidget添加数据
时间: 2023-08-08 15:13:08 浏览: 137
pyqt5 TableWidget
要在PyQt5的QTableWidget中添加数据,可以按照以下步骤进行操作:
1. 实例化一个QTableWidget对象,并设置列数。例如:
```python
self.table = QtWidgets.QTableWidget()
self.table.setColumnCount(4)
```
2. 设置表格中的内容,并使内容居中。可以使用setItem()方法来设置每个单元格的内容,并使用setTextAlignment()方法来设置文本居中显示。例如:
```python
self.tableWidget.setItem(0, 0, QTableWidgetItem(str(query.value(8))))
self.tableWidget.setItem(0, 1, QTableWidgetItem('板载温度').setTextAlignment(Qt.AlignCenter))
self.tableWidget.setItem(0, 2, QTableWidgetItem(str(query.value(4))))
```
3. 提取数据并显示在表格中。可以使用fetchall()方法获取数据,并将其存储在一个列表中。然后,遍历列表并使用setItem()方法将数据添加到表格中。例如:
```python
data = cur.fetchall()
list_data = \[\]
all_id = \[0, 0, 0, 0\]
all_name = \[0, 0, 0, 0\]
for x in range(0, len(data)):
all_id\[x\] = data\[x\].get('id')
all_name\[x\] = data\[x\].get('name')
list_data.append(all_id\[x\])
list_data.append(all_name\[x\])
for i in range(len(data)):
for j in range(2):
if j == 0:
one_item = QtWidgets.QTableWidgetItem(str(list_data\[num_id\]))
num_id += 2
self.tableWidget.setItem(i, j, one_item)
else:
two_item = QtWidgets.QTableWidgetItem(str(list_data\[num_name\]))
num_name += 2
self.tableWidget.setItem(i, j, two_item)
```
这样就可以将数据添加到PyQt5的QTableWidget中了。
#### 引用[.reference_title]
- *1* [pyqt5的QTableWidget动态添加数据并获取单元格内容](https://blog.csdn.net/gefeng0510/article/details/108007307)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [PyQt5中动态设置QTableWidget表格添加数据,并且设置表格的行高,列宽](https://blog.csdn.net/u014535666/article/details/104750373)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [python,pyqt5,QTableWidgetItem插入内容,报错item = QtWidgets.QTableWidgetItem(str(data[i][j])) Key...](https://blog.csdn.net/qq_57663276/article/details/128244977)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文