BackGroundColor for row in QTableView

Heads up! You've already completed this tutorial.

zadstofun | 2021-03-11 10:32:22 UTC | #1

Hello,

I'm trying to generate a TableView from a list of dict my data sample is like this

python
data = [{'IP': '192.168.1.10', 'PRESENT_STATUS': 'NewConnection'},
        {'IP': '192.168.1.108', 'FORMER_STATUS': 'NewConnection, 'PRESENT_STATUS': 'Registered'}]

My understanding of the below code is that data method gets all possible roles one after the other for each index.row() and index.col().

This means that when role == Qt.BackgroundRole and the color for the present status is defined self._base_color dict, the column gets painted.

I know that my code below should paint the entire row albeit doing it column wise.

python
class TableModel(QAbstractTableModel):

    def __init__(self, data: Union[list, dict] = None):
        super().__init__()
        self.data = data or []
        self._hdr = self.gen_hdr_data() if data else []
        self._base_color = {'NewConnection': 'blue', }

    def gen_hdr_data(self):
        self._hdr = sorted(list(set().union(*(d.keys() for d in self.data))))
        return self._hdr

    def data(self, index: QModelIndex, role: int):
         _state = self.data[index.row()]['PRESENT_STATUS']
        if role == Qt.DisplayRole:
            try:
                col = self._hdr[index.column()]
                value = self.data[index.row()][col]
            except KeyError:
                value = None
            return str(value) if value else ""

        if role == Qt.BackgroundRole and self._base_color.get(_state, False):
            return QColor(self._base_color[_state])

My question is goes as such:

Is it possible to perform a row background paint rather than a column wise action?


Packaging Python Applications with PyInstaller by Martin Fitzpatrick — This step-by-step guide walks you through packaging your own Python applications from simple examples to complete installers and signed executables.

More info Get the book

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak
Martin Fitzpatrick

BackGroundColor for row in QTableView was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt.