| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import sys
- import pandas as pd
- from PyQt5.QtCore import QAbstractTableModel, Qt
- from PyQt5.QtWidgets import QMainWindow, QTableView, QApplication
- class TableModel(QAbstractTableModel):
- def __init__(self, data):
- super(TableModel, self).__init__()
- self._data = data
- def data(self, index, role):
- if role == Qt.DisplayRole:
- value = self._data.iloc[index.row(), index.column()]
- return str(value)
- def rowCount(self, index):
- return self._data.shape[0]
- def columnCount(self, index):
- return self._data.shape[1]
- def headerData(self, section, orientation, role):
- if role == Qt.DisplayRole:
- if orientation == Qt.Horizontal:
- return str(self._data.columns[section])
- if orientation == Qt.Vertical:
- return str(self._data.index[section])
- class MainWindow(QMainWindow):
- def __init__(self):
- super().__init__()
- self.table = QTableView()
- data = pd.DataFrame(
- [
- [1, 9, 2],
- [4, 0, -1],
- [7, 8, 9],
- [3, 3, 2],
- [5, 8, 9],
- ],
- columns=['a', 'b', 'c'],
- index=['Row 1', 'Row 2', 'Row 3', 'Row 4', 'Row 5'],
- )
- self.model = TableModel(data)
- self.table.setModel(self.model)
- self.setCentralWidget(self.table)
- self.setGeometry(600, 100, 400, 200)
- app = QApplication(sys.argv)
- window = MainWindow()
- window.show()
- sys.exit(app.exec_())
|