Question

I am working on a sample app where I need to disable the text of a checkbox when the checkbox is not checked and enable it when checked.

Code:

if(ui->checkBox->isChecked() == true)
{
   // Enable the text of the checkbox
}

else
{
   // Disable the text of the checkbox      
}

I have looked through various articles but I haven't found the right solution.

Was it helpful?

Solution

Use a stylesheet

For all your widget:

ui->setStyleSheet(
"QCheckBox:checked {
     {color: black;}
 }
 QCheckBox:unchecked {
     {color: grey;}
 }"
)

Edit:

As mentioned in comment, To make it work with custom themes, you can make the style querying the palette:

QPalette my_palette = ui->palette()
QColor my_active_color = my_palette.color(QPalette::Active, QPalette::Text);
QColor my_disabled_color = my_palette.color(QPalette::Disabled, QPalette::Text);

QString my_style =
 QString("QCheckBox:checked { {color: rgb(%1, %2, %3);} } "     
"QCheckBox:unchecked { {color: rgb(%4, %5, %6);}}")
.arg( my_active_color.red())
.arg( my_active_color.green())
.arg( my_active_color.blue() )
.arg( my_disabled_color.red())
.arg( my_disabled_color.green())
.arg( my_disabled_color.blue() );

ui->setStyleSheet(my_style);

Note that i dindn't tried it and it could have any typo, but you get the idea.

OTHER TIPS

I got the solution. This is how I achieved it:

ui->checkBox->setStyleSheet( "QCheckBox:checked{color: black;} QCheckBox:unchecked{color: grey;}");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top