QStyledItemDelegate - get table item's current background color?

  • Hello,

    Trying to implement a transparent selection by using a QStyledItemDelegate and overriding the paint method:

    def paint(self, painter, option, index):
        if option.state & QtWidgets.QStyle.State_Selected:
            var = index.model()
            color = var.data(index, QtCore.Qt.BackgroundRole)
            text = var.data(index, QtCore.Qt.DisplayRole)
            painter.fillRect(option.rect, color.color())
            painter.drawText(option.rect, QtCore.Qt.AlignCenter, text)
            QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)

    My table item, from a TableWidget, already has a color set (blue). So how can I get the current background of the cell and set the selected color to that? Setting color.color() gives me a black background and just using the QBrush itself color gives me the default grey.

    (Text is slightly off too, I'd prefer to have it maintain its original settings)

  • Lifetime Qt Champion


    Do you mean you don't want to paint anything special when the item is selected ?

  • @SGaist Yep that's what I want, I know I can do something like this for that:

    option.state &= ~QtWidgets.QStyle.State_Selected in initStyleOption

    But I was planning on adding a border too so getting the background color itself would be ideal.

  • Lifetime Qt Champion

    What style of border ?

  • @SGaist Just a simple lined border. At present, this border applies behind the background and isn't visible. There's also the issue of the existing dotted border that I'd want to remove/replace.

Log in to reply