Method 1 Set dynamic properties for each sub-control
UIText item setting arrangement qss:
QPushButton#option {
background: #FFFFFF;
color: #999999;
}
// option和[之间不能有空格
QPushButton#option[itemSelected = "true"] {
background:rgb(65,205,82);
color:white;
}
QLabel#text {
color: #333333;
}
QLabel#text[itemSelected = "true"] {
color:rgb(65,205,82);
}
In the code:
代码里:
if (selected)
{
ui->option->setProperty("itemSelected", "true");
ui->text->setProperty("itemSelected", "true");
}
else
{
ui->option->setProperty("itemSelected", "false");
ui-> text ->setProperty("itemSelected", " false ");
}
//ui->option->style()->unpolish(ui->option);
//ui->option->style()->polish(ui->option);
ui->option->setStyle(qApp->style());
ui->text->setStyle(qApp->style());
setStyle is just one line of code
Method 2 Specify the child control style under the dynamic properties of the parent widget, so that each child control does not need to setProperty (simpler)< /span>
UIText item setting arrangement qss:
QWidget#OptionItem QPushButton {
background: #FFFFFF;
color: #999999;
}
QWidget#OptionItem[itemSelected = "true"] QPushButton {
background:rgb(65,205,82);
color:white;
}
QWidget#OptionItem QLabel {
color: #333333;
}
QWidget#OptionItem[itemSelected = "true"] QLabel {
color:rgb(65,205,82);
}
In the code:
connect(ui->optionListWidget, &QListWidget::currentItemChanged, [this](QListWidgetItem* current, QListWidgetItem* previous) {
OptionItem *curItem = qobject_cast<OptionItem*>(ui->optionListWidget->itemWidget(current));
if (curItem)
{
curItem->setProperty("itemSelected", "true");
curItem->setStyle(qApp->style());
}
OptionItem* prevItem = qobject_cast<OptionItem*>(ui->optionListWidget->itemWidget(previous));
if (prevItem)
{
prevItem->setProperty("itemSelected", "false");
prevItem->setStyle(qApp->style());
}
});