存进sqlite数据库中的数据如何在QtableWidget中显示
时间: 2024-03-26 07:35:16 浏览: 74
可以通过以下步骤将SQLite数据库中的数据显示在QTableWidget中:
1. 连接SQLite数据库,并查询需要的数据。
```python
import sqlite3
# 连接SQLite数据库
conn = sqlite3.connect('example.db')
# 查询数据
cursor = conn.execute("SELECT * from table_name")
rows = cursor.fetchall()
```
2. 在QTableWidget中设置列数和行数,以及表头。
```python
# 设置QTableWidget的列数和行数
table_widget.setColumnCount(len(rows[0]))
table_widget.setRowCount(len(rows))
# 设置QTableWidget的表头
header = [description[0] for description in cursor.description]
table_widget.setHorizontalHeaderLabels(header)
```
3. 将查询结果填充到QTableWidget中。
```python
# 将查询结果填充到QTableWidget中
for i, row in enumerate(rows):
for j, value in enumerate(row):
item = QtWidgets.QTableWidgetItem(str(value))
table_widget.setItem(i, j, item)
```
完整代码示例:
```python
import sqlite3
from PyQt5 import QtWidgets
# 连接SQLite数据库
conn = sqlite3.connect('example.db')
# 查询数据
cursor = conn.execute("SELECT * from table_name")
rows = cursor.fetchall()
# 创建QTableWidget
app = QtWidgets.QApplication([])
table_widget = QtWidgets.QTableWidget()
# 设置QTableWidget的列数和行数
table_widget.setColumnCount(len(rows[0]))
table_widget.setRowCount(len(rows))
# 设置QTableWidget的表头
header = [description[0] for description in cursor.description]
table_widget.setHorizontalHeaderLabels(header)
# 将查询结果填充到QTableWidget中
for i, row in enumerate(rows):
for j, value in enumerate(row):
item = QtWidgets.QTableWidgetItem(str(value))
table_widget.setItem(i, j, item)
# 显示QTableWidget
table_widget.show()
app.exec_()
```
需要注意的是,以上代码中仅演示了如何将查询结果填充到QTableWidget中,具体实现方式还需要根据实际需求进行调整。例如,如果需要在QTableWidget中编辑数据并保存到SQLite数据库中,还需要实现相应的事件处理函数。
阅读全文
相关推荐
















