tableview_pandas.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import sys
  2. import pandas as pd
  3. from PyQt5.QtCore import QAbstractTableModel, Qt
  4. from PyQt5.QtWidgets import QMainWindow, QTableView, QApplication
  5. class TableModel(QAbstractTableModel):
  6. def __init__(self, data):
  7. super(TableModel, self).__init__()
  8. self._data = data
  9. def data(self, index, role):
  10. if role == Qt.DisplayRole:
  11. value = self._data.iloc[index.row(), index.column()]
  12. return str(value)
  13. def rowCount(self, index):
  14. return self._data.shape[0]
  15. def columnCount(self, index):
  16. return self._data.shape[1]
  17. def headerData(self, section, orientation, role):
  18. if role == Qt.DisplayRole:
  19. if orientation == Qt.Horizontal:
  20. return str(self._data.columns[section])
  21. if orientation == Qt.Vertical:
  22. return str(self._data.index[section])
  23. class MainWindow(QMainWindow):
  24. def __init__(self):
  25. super().__init__()
  26. self.table = QTableView()
  27. data = pd.DataFrame([
  28. [1, 9, 2],
  29. [4, 0, -1],
  30. [7, 8, 9],
  31. [3, 3, 2],
  32. [5, 8, 9],
  33. ],
  34. columns=['a', 'b', 'c'], index=['Row 1', 'Row 2', 'Row 3', 'Row 4', 'Row 5'],
  35. )
  36. self.model = TableModel(data)
  37. self.table.setModel(self.model)
  38. self.setCentralWidget(self.table)
  39. self.setGeometry(600, 100, 400, 200)
  40. app = QApplication(sys.argv)
  41. window = MainWindow()
  42. window.show()
  43. sys.exit(app.exec_())