0

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_()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Max
  • 3
  • 1
  • " I would like the model to display a tick mark whenever the value 'status' in a cell is True". Models do not display anything, views and delegates do, based on the data in the model. Which view are you using? (It apparently doesn't ask about DecorationRole). Also try Qt::CheckstateRole. – Frank Osterfeld Aug 20 '20 at 16:21
  • I see that it works correctly, add `print(role, Qt.DecorationRole)` before `if role == Qt.DisplayRole:` tell me what you get – eyllanesc Aug 20 '20 at 16:26
  • I am getting: 6 1 7 1 9 1 10 1 # the next sequence for a total of 3 times 1 1 0 1 8 1 6 1 7 1 9 1 10 1 # end sequence 1 1 0 1 8 1 – Max Aug 20 '20 at 16:50
  • So basically role cycles through 1, 0, 8, 6, 7, 9, 10 and Qt.DecorationRole is always 1 – Max Aug 20 '20 at 16:57

0 Answers0