4
votes

I am changing the foreground and background color of some of the cells in a QTableWdiget to highlight certain items. I want to later remove the highlighting and restore the default foreground and background colors to the cell, but I'm having trouble doing this.

At the moment I'm resetting the colors to black text on a white background, which will be right on most systems. However, on some systems these will be the wrong colours, e.g. systems using high viability themes where the text is white and the background is black.

I therefore want to find a way to restore the default colors to a cell in the QTableWidget. To do this I tried to backup the default colors before changing them, but this does not save the correct colors:

QColor fgCol = table->item(0, 0)->foreground().color();
QColor bgCol = table->item(0, 0)->background().color();

I also tried this, but it doesn't work either:

QColor fgCol = table->item(0, 0)->data(Qt::ForegroundRole).value<QBrush>().color();
QColor bgCol = table->item(0, 0)->data(Qt::BackgroundRole).value<QBrush>().color();

Is there a way I can restore the default colours to a QTableWidgetItem?

1
Pretty sure they return invalid colors (see isValid()), not black...peppe
@peppe Sorry, yes you're right. It just shows up as black. Either way, it looks like that's not going to work. I need some way to restore a QTableWidget item back to its original foreground and background colors after changing them, but I can't seem to fine a function to do this.Ian Conner
Not even a setData(QVariant(), Qt::BackgroundRole) or similar?peppe
@peppe The problem I'm having isn't setting the color, but knowing what default color is to restore. I'll edit my question to try and make it clearer.Ian Conner

1 Answers

1
votes

You need to backup the brushes, not just the colors:

QBrush fgBrush = table->item(0, 0)->foreground();
QBrush bgBrush = table->item(0, 0)->background();

and restore them later:

table->item(0, 0)->setForeground(fgBrush);
table->item(0, 0)->setBackground(bgBrush);