0

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.

Daniel Hedberg
  • 5,677
  • 4
  • 36
  • 61
Gojira
  • 171
  • 4
  • 14

2 Answers2

1

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.

trompa
  • 1,967
  • 1
  • 18
  • 26
  • 3
    What happens if the user has custom color scheme with white text? If you skin some widgets, you should skin the whole application so that everything is consistent. Hardcoded colors can't be used here, enabled and disabled text colors should be taken from current palette. – Paul Apr 24 '13 at 11:15
  • @Trompa: I tried this: `ui->checkBox->setStyleSheet( "QCheckBox::indicator:checked { {color: black;} } QCheckBox::indicator:unchecked {{color: grey;}}");` but It doesnt seem to work..... – Gojira Apr 24 '13 at 11:17
  • 1
    If you are applying the style in a per widget basis, try this way: myWidget->setStyleSheet("color: blue"); – trompa Apr 24 '13 at 12:16
  • You can use `name()` method of QColor, instead of `red`, `green` and `blue`. It returns string hex color value. – Mykola Niemtsov Mar 09 '16 at 17:57
0

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

ui->checkBox->setStyleSheet( "QCheckBox:checked{color: black;} QCheckBox:unchecked{color: grey;}");
Gojira
  • 171
  • 4
  • 14
  • So, you didnt need the indicator part... bad Qt docs ... I will edit my answer then, in case someone else comes to this question – trompa Apr 24 '13 at 12:46