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?


The complete guide to packaging Python GUI applications with PyInstaller.
[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]
Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

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.