2014-10-09 174 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