I was trying to build a simple QAbstractTableModel to familiarize myself with the concepts.
The model I build however, is not behaving as I anticipated. I would like the model to display a tick mark whenever the value 'status' in a cell is True.
The condition if role == Qt.DecorationRole
is never true. Therefore my question: where do I set the flag for role or how do I make sure the Qt.DecorationRole gets set?
The minimal code looks like this:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
import pandas as pd
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def data(self, index, role):
if role == Qt.DisplayRole:
status, value = self._data.iloc[index.row(), index.column()]
return str(value)
if role == Qt.DecorationRole:
status, value = self._data.iloc[index.row(), index.column()]
if status:
return QtGui.QIcon('tick.png')
def rowCount(self, index):
return self._data.shape[0]
def columnCount(self, index):
return self._data.shape[1]
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return str(self._data.columns[section])
if orientation == Qt.Vertical:
return str(self._data.index[section])
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
data = pd.DataFrame([
[(False, 1), (True, 9)],
[(True, 1), (False, 0)],
], columns=['A', 'B'], index=['Row 1', 'Row 2'])
self.model = TableModel(data)
self.table.setModel(self.model)
self.setCentralWidget(self.table)
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()