Set widget background color

I am using 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 to change cell background?

+7
qt qtablewidget qcheckbox
source share
3 answers

The code:

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

works fine, but you need to set a style for each container widget that you add to the table:

So, to see the change, you will 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

+7
source share

You should try the following:

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

If you want to specify it in more detail, write classtype in CSS to indicate which class in the hierarchy should handle the flag. Then it might look something like this:

 QWidget { background-color: red; } 
+1
source share

If you want to change the background of the cell, not the widget, use the setBackground() method:

 QCheckBox *checkBox = new QCheckBox("example"); QWidget *widget = new QWidget(); QHBoxLayout *layout = new QHBoxLayout(widget); layout->addWidget(checkBox); layout->setAlignment(Qt::AlignCenter); layout->setContentsMargins(0, 0, 0, 0); widget->setLayout(layout); ui->tableWidget_2->setCellWidget(0,0,widget); ui->tableWidget_2->item(0, 0)->setBackground(Qt::red);//this line should be 

In this case, your whole cell will be red (without white lines around the check box).

+1
source share

All Articles