2014-10-09 21 views
7

Io uso QCheckBox in QTableWidgetCellImposta sfondo widget di colore

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

Come posso cambiare sfondo della cella?

risposta

7

Il codice:

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

funziona bene, ma è necessario impostare lo stile per ogni widget di contenitore che si aggiunge al tuo tavolo:

Quindi, al fine di vedere il cambiamento è necessario il seguente codice:

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

E il risultato sarà:

enter image description here

+0

Funziona. Ma solo l'ultimo sfondo modificato della cella ha impostato lo sfondo. Recupero degli sfondi delle celle precedenti. – Ufx

+0

@Ufx Vedi le mie modifiche –

1

Si dovrebbe provare questo:

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

Se si desidera specificare più in generale, prego scrivere la ClassType nel CSS per indicare quale classe nella gerarchia dovrebbe gestire la bandiera. Questo potrebbe essere simile a questo allora:

QWidget { background-color: red; } 
+0

Questo non funziona. – Ufx

+0

@ufx CHE COSA non funziona? Come appare ora? – msrd0

+0

Funziona come se non funzionasse affatto. Nessuna reazione. – Ufx

1

Se si desidera cambiare sfondo della cella, non è un widget, utilizzare setBackground() metodo:

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 questo caso tutto il vostro cellulare sarà rosso (senza bianco righe intorno alla casella di controllo).

+0

Non funziona per me – Ufx

+0

ui-> tableWidget_2-> item (0, 0) -> setBackground (Qt :: red); è pericoloso perché .setCellWidget non crea un elemento su quella cella che restituisce il puntatore nullo – Phiber