tableview_demo.py 2.9 KB

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