设置小部件的背景颜色

9

我在QTableWidgetCell中使用QCheckBox

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

我该如何更改单元格背景?

3个回答

9
代码如下:
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);

结果将是:

在此输入图像描述


(注:该内容为HTML格式,请勿删除)

它可以工作。但是只有最后更改背景的单元格设置了背景。以前的单元格背景恢复了。 - Ufx

1
你应该尝试这个:

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

如果您想更加通用地指定它,请在CSS中编写classtype以指示应由层次结构中的哪个类处理标志。然后可能会看起来像这样:
QWidget { background-color: red; }

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

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

ui->tableWidget_2->item(0, 0)->setBackground(Qt::red); 是危险的,因为 .setCellWidget 不会在该单元格上创建项目,从而返回空指针。 - Phiber
最后一行会导致崩溃,因为item(0,0)返回了一个空指针。 - PlinyTheElder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接