tableview_pandas.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. [
  29. [1, 9, 2],
  30. [4, 0, -1],
  31. [7, 8, 9],
  32. [3, 3, 2],
  33. [5, 8, 9],
  34. ],
  35. columns=['a', 'b', 'c'],
  36. index=['Row 1', 'Row 2', 'Row 3', 'Row 4', 'Row 5'],
  37. )
  38. self.model = TableModel(data)
  39. self.table.setModel(self.model)
  40. self.setCentralWidget(self.table)
  41. self.setGeometry(600, 100, 400, 200)
  42. app = QApplication(sys.argv)
  43. window = MainWindow()
  44. window.show()
  45. sys.exit(app.exec_())