Set widget background color

Ufx picture Ufx · Oct 9, 2014 · Viewed 29.4k times · Source

I use QCheckBox in QTableWidgetCell

QWidget *widget = new QWidget();
QCheckBox *checkBox = new QCheckBox();
QHBoxLayout *layout = new QHBoxLayout(widget);
layout->addWidget(checkBox);
layout->setAlignment(Qt::AlignCenter);
layout->setContentsMargins(0, 0, 0, 0);
widget->setLayout(layout);
table->setCellWidget(0, 0, widget);

How can I change cell background?

Answer

Jacob Krieg picture Jacob Krieg · Oct 9, 2014

The code:

widget->setStyleSheet("background-color: red");

works fine but you need to set the style for every container widget you add to your table:

So in order to see the change you need the following code:

QWidget *widget = new QWidget();
widget->setStyleSheet("background-color: red");
QCheckBox *checkBox = new QCheckBox();
QHBoxLayout *layout = new QHBoxLayout(widget);
layout->addWidget(checkBox);
layout->setAlignment(Qt::AlignCenter);
layout->setContentsMargins(0, 0, 0, 0);
widget->setLayout(layout);

QWidget *widget2 = new QWidget();
widget2->setStyleSheet("background-color: red");
QCheckBox *checkBox2 = new QCheckBox();
QHBoxLayout *layout2 = new QHBoxLayout(widget2);
layout2->addWidget(checkBox2);
layout2->setAlignment(Qt::AlignCenter);
layout2->setContentsMargins(0, 0, 0, 0);
widget2->setLayout(layout);

ui->tableWidget->setCellWidget(0, 0, widget);
ui->tableWidget->setCellWidget(0, 1, widget2);

And the result will be:

enter image description here