28

If a cell have some data, using

tableWidget->item(8,0)->setBackgroundColor(Qt::red);

to change the background color will work, but if a cell is blank it will fail.

Daniel Hedberg
  • 5,677
  • 4
  • 36
  • 61
spy8888
  • 315
  • 1
  • 5
  • 9

1 Answers1

39

You cannot set the background color of a cell unless it contains a QTableWidgetItem (as the background color is a property of the item).

So you need to populate your QTableWidget with empty items first. In your example, create the item before you attempt to set the background color.

tableWidget->setItem(8, 0, new QTableWidgetItem);
tableWidget->item(8, 0)->setBackground(Qt::red);

Please also note that you should use setBackground instead of setBackgroundColor as the latter is deprecated.

Daniel Hedberg
  • 5,677
  • 4
  • 36
  • 61
  • 1
    Fixed a similar problem for me. Any idea why this works and `->background.setColor()` does not? – T.E.D. May 20 '14 at 20:47