Is it possible to change the color in PyQt5 TableView via delegate?

Viewed 245

I'm using a PyQt5 QTableView to display a SQL table in my GUI. In order to align the values in the last column, I use this:

delegate = AlignDelegate(self.view)
self.view.setItemDelegateForColumn(3, delegate)

class AlignDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(AlignDelegate, self).initStyleOption(option, index)
        option.displayAlignment = (QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)

Now I wonder if I could add something to AlignDelegate in order to also change the color of the displayed numbers (painting negative numbers red). I didn't find a working solution, so it would be really nice if someone could give me a hint.

I'm using Python 3.8, PyQt5 5.15.0, PyCharm 2020.2 and Linux Mint 19.3.

1 Answers

You have to change the palette of QStyleOptionViewItem to change the text color and backgroundBrush of QStyleOptionViewItem to change the background color.

class AlignDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(AlignDelegate, self).initStyleOption(option, index)
        option.displayAlignment = QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter
        value = index.data()
        if value < 0:
            option.palette.setBrush(
                QtGui.QPalette.Text, QtGui.QBrush(QtGui.QColor("red"))
            )
            option.backgroundBrush = QtGui.QBrush(QtGui.QColor("green"))
Related