BackGroundColor for row in QTableView

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:

PyQt/PySide 1:1 Coaching with Martin Fitzpatrick — Get one on one help with your Python GUI projects. Working together with you I'll identify issues and suggest fixes, from bugs and usability to architecture and maintainability.

Book Now 60 mins ($195)

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

Over 10,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt5
Take a look

Downloadable ebook (PDF, ePub) & Complete Source code

Also available from Leanpub and Amazon Paperback


Create GUI Applications with Python & Qt6 by Martin Fitzpatrick — (PyQt6 Edition) The hands-on guide to making apps with Python — Over 10,000 copies sold!

More info Get the book

Mark As Complete
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. Martin founded PythonGUIs to provide easy to follow GUI programming tutorials to the Python community. He has written a number of popular Python books on the subject.