我在QCheckBox
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);
如何更改单元格背景?
答案 0 :(得分: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);
结果将是:
答案 1 :(得分:1)
你应该试试这个:
checkBox->setStyleSheet("background-color: red;");
如果要更一般地指定它,请在CSS中编写classtype以指示层次结构中的哪个类应该处理该标志。这可能看起来像这样:
QWidget { background-color: red; }
答案 2 :(得分: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
在这种情况下,您的所有单元格都将为红色(复选框周围没有白线)。