1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
| import sys
import pandas as pd
from PySide6.QtWidgets import (
QApplication, QMainWindow, QTableView, QVBoxLayout, QWidget
)
from PySide6.QtCore import Qt, QAbstractTableModel
class PandasTableModel(QAbstractTableModel):
def __init__(self, df: pd.DataFrame):
super().__init__()
self.df = df
def rowCount(self, parent=None):
return len(self.df)
def columnCount(self, parent=None):
return self.df.columns.size
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return None
row = index.row()
col = index.column()
if role == Qt.DisplayRole:
val = self.df.iloc[row, col]
return str(val)
return None
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role != Qt.DisplayRole:
return None
if orientation == Qt.Horizontal:
return str(self.df.columns[section])
return str(section)
def flags(self, index):
if not index.isValid():
return Qt.NoItemFlags
return super().flags(index) | Qt.ItemIsEditable
def setData(self, index, value, role=Qt.EditRole):
if not index.isValid() or role != Qt.EditRole:
return False
row = index.row()
col = index.column()
self.df.iloc[row, col] = value
self.dataChanged.emit(index, index, [Qt.DisplayRole])
return True
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("自定义 QAbstractTableModel + Pandas")
self.resize(700, 400)
df = pd.DataFrame([
{"id": 1, "name": "张三", "age": 24, "city": "武汉"},
{"id": 2, "name": "李四", "age": 28, "city": "杭州"},
{"id": 3, "name": "王五", "age": 31, "city": "深圳"},
])
self.model = PandasTableModel(df)
self.table = QTableView()
self.table.setModel(self.model)
self.table.horizontalHeader().setStretchLastSection(True)
layout = QVBoxLayout()
layout.addWidget(self.table)
central = QWidget()
central.setLayout(layout)
self.setCentralWidget(central)
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec())
|