tableview_demo.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import sys
  2. from datetime import datetime
  3. from PyQt5.QtCore import QAbstractTableModel, Qt
  4. from PyQt5.QtGui import QColor
  5. from PyQt5.QtWidgets import QTableView, QMainWindow, QApplication
  6. COLORS = [
  7. '#053061', '#2166ac', '#4393c3', '#92c5de', '#d1e5f0', '#f7f7f7',
  8. '#fddbc7', '#f4a582', '#d6604d', '#b2182b', '#67001f'
  9. ]
  10. class TableModel(QAbstractTableModel):
  11. def __init__(self, data):
  12. super(TableModel, self).__init__()
  13. self._data = data
  14. def data(self, index, role):
  15. if role == Qt.DecorationRole:
  16. value = self._data[index.row()][index.column()]
  17. if isinstance(value, int) or isinstance(value, float):
  18. value = int(value)
  19. value = max(-5, value) # value < -5 becomes -5
  20. value = min(5, value) # value > 5 becomes 5
  21. value = value + 5 # -5 becomes 0, 5 becomes 10
  22. return QColor(COLORS[value])
  23. if role == Qt.ForegroundRole:
  24. value = self._data[index.row()][index.column()]
  25. if (isinstance(value, int)
  26. or isinstance(value, float)) and value < 0:
  27. return QColor(Qt.red)
  28. if role == Qt.TextAlignmentRole:
  29. value = self._data[index.row()][index.column()]
  30. if isinstance(value, int) or isinstance(value, float):
  31. # Align right, vertical middle.
  32. return Qt.AlignVCenter + Qt.AlignRight
  33. if role == Qt.DisplayRole:
  34. # See below for the nested-list data structure.
  35. # .row() indexes into the outer list,
  36. # .column() indexes into the sub-list
  37. value = self._data[index.row()][index.column()]
  38. if isinstance(value, datetime):
  39. # Here, we use the date's string representation.
  40. return value.strftime('%Y-%m-%d')
  41. if isinstance(value, str):
  42. # Here, we use the date
  43. return '"%s"' % value
  44. if isinstance(value, float):
  45. # Here, we use the date
  46. return "%.2f" % value
  47. return value
  48. def rowCount(self, index):
  49. # The length of the outer list.
  50. return len(self._data)
  51. def columnCount(self, index):
  52. # The following takes the first sub-list, and returns
  53. # the length (only works if all rows are an equal length)
  54. return len(self._data[0])
  55. class MainWindow(QMainWindow):
  56. def __init__(self, *args, **kwargs):
  57. super().__init__(*args, **kwargs)
  58. self.table = QTableView()
  59. data = [
  60. [4, 9, 2],
  61. [1, -1, 'hello'],
  62. [3.141592653589793, 2.718281828459045, 'world'],
  63. [3, 3, datetime(2025, 2, 18)],
  64. [7, 1, -5],
  65. ]
  66. self.model = TableModel(data)
  67. self.table.setModel(self.model)
  68. self.setCentralWidget(self.table)
  69. app = QApplication(sys.argv)
  70. window = MainWindow()
  71. window.show()
  72. sys.exit(app.exec_())