将pandas表格数据复制到PyQt5表中 用QTableWidget
时间: 2024-10-06 12:05:53 浏览: 28
将Pandas DataFrame的数据复制到PyQt5的QTableWidget中,首先需要安装相关的库,如`pandas`, `pyqt5`等。以下是步骤:
1. 导入库:
```python
import pandas as pd
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem
from PyQt5.QtCore import Qt
```
2. 创建DataFrame:
```python
# 假设df是一个已经创建好的Pandas DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [20, 25, 30]}
df = pd.DataFrame(data)
```
3. 初始化PyQt5窗口和QTableWidget:
```python
app = QApplication([])
window = QMainWindow()
table_widget = QTableWidget(window)
table_widget.setGeometry(100, 100, 400, 300) # 设置大小
```
4. 设置列标题和数据到QTableWidget:
```python
# 添加列头
headers = df.columns.tolist()
table_widget.setHorizontalHeaderLabels(headers)
# 将DataFrame数据填充到QTableWidget中
for i, row in df.iterrows():
for j, col in enumerate(row):
table_widget.setItem(i, j, QTableWidgetItem(str(col)))
```
5. 显示并运行窗口:
```python
table_widget.resizeColumnsToContents() # 自动调整列宽
table_widget.resizeRowsToContents()
window.show()
app.exec_()
```
通过上述代码,Pandas DataFrame的内容就会显示在QTableWidget上。
阅读全文