2014-10-09 107 views
7

我用QCheckBoxQTableWidgetCell设置控件的背景色

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); 

如何更改单元格的背景?

回答

7

代码:

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

工作正常,但你需要设置样式为每个容器控件添加到您的表:

所以为了看你需要下面的代码的变化:

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); 

而结果将是:

enter image description here

+0

它的工作原理。但只有最后一个背景改变了细胞已经设置了背景先前的细胞背景已恢复 – Ufx 2014-10-10 03:13:51

+0

@Ufx查看我的编辑 – 2014-10-10 07:48:02

1

你应该试试这个:

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

如果你想更普遍的指定,在CSS编写CLASSTYPE以指示类层次结构中应该处理的标志。这可能是这个样子,那么:

QWidget { background-color: red; } 
+0

这不起作用。 – Ufx 2014-10-09 19:17:29

+0

@ufx什么不起作用?它现在看起来如何? – msrd0 2014-10-09 19:18:05

+0

它的工作方式完全不起作用。没有反应。 – Ufx 2014-10-09 19:23:50

1

如果要更改单元格背景,而不是一个小部件,使用setBackground()方法:

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 

在这种情况下,所有你的将是红色的(没有白复选框周围的线)。

+0

对我不起作用 – Ufx 2014-10-10 01:13:53

+0

ui-> tableWidget_2-> item(0,0) - > setBackground(Qt :: red);是危险的,因为.setCellWidget不会在该单元格上创建返回空指针的项目 – Phiber 2018-02-05 18:44:06