| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- import sys
- from datetime import datetime
- from PyQt5.QtCore import QAbstractTableModel, Qt
- from PyQt5.QtGui import QColor
- from PyQt5.QtWidgets import QTableView, QMainWindow, QApplication
- COLORS = [
- '#053061', '#2166ac', '#4393c3', '#92c5de', '#d1e5f0', '#f7f7f7',
- '#fddbc7', '#f4a582', '#d6604d', '#b2182b', '#67001f'
- ]
- class TableModel(QAbstractTableModel):
- def __init__(self, data):
- super(TableModel, self).__init__()
- self._data = data
- def data(self, index, role):
- if role == Qt.DecorationRole:
- value = self._data[index.row()][index.column()]
- if isinstance(value, int) or isinstance(value, float):
- value = int(value)
- value = max(-5, value) # value < -5 becomes -5
- value = min(5, value) # value > 5 becomes 5
- value = value + 5 # -5 becomes 0, 5 becomes 10
- return QColor(COLORS[value])
- if role == Qt.ForegroundRole:
- value = self._data[index.row()][index.column()]
- if (isinstance(value, int)
- or isinstance(value, float)) and value < 0:
- return QColor(Qt.red)
- if role == Qt.TextAlignmentRole:
- value = self._data[index.row()][index.column()]
- if isinstance(value, int) or isinstance(value, float):
- # Align right, vertical middle.
- return Qt.AlignVCenter + Qt.AlignRight
- if role == Qt.DisplayRole:
- # See below for the nested-list data structure.
- # .row() indexes into the outer list,
- # .column() indexes into the sub-list
- value = self._data[index.row()][index.column()]
- if isinstance(value, datetime):
- # Here, we use the date's string representation.
- return value.strftime('%Y-%m-%d')
- if isinstance(value, str):
- # Here, we use the date
- return '"%s"' % value
- if isinstance(value, float):
- # Here, we use the date
- return "%.2f" % value
- return value
- def rowCount(self, index):
- # The length of the outer list.
- return len(self._data)
- def columnCount(self, index):
- # The following takes the first sub-list, and returns
- # the length (only works if all rows are an equal length)
- return len(self._data[0])
- class MainWindow(QMainWindow):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.table = QTableView()
- data = [
- [4, 9, 2],
- [1, -1, 'hello'],
- [3.141592653589793, 2.718281828459045, 'world'],
- [3, 3, datetime(2025, 2, 18)],
- [7, 1, -5],
- ]
- self.model = TableModel(data)
- self.table.setModel(self.model)
- self.setCentralWidget(self.table)
- app = QApplication(sys.argv)
- window = MainWindow()
- window.show()
- sys.exit(app.exec_())
|