Set a button of custom color to a disabled style

16.2k views Asked by At

I have a class that inherits QWidget. Under certain circumstances, I wish to set it disabled.

The widget has some color buttons, that are set from a list of colors:

void MyWidget::colorUpdate(QString color)
{
    if(!color.isEmpty())
    {
        QString foreground = (QColor(color).lightness() < 125 ? "white" : "black");
        m_colorButton->setStyleSheet("color: " + foreground + "; background-color: " + color);
    }
}

Calling myWidget.setEnabled(enabledOption); disables the widget, grays out all text and every other items in the widget - except for these color buttons.

So I am thinking of making my own action:

void MyWidget::setWidgetEnabled(bool enabled)
{
    this->setEnabled(enabled);
    // what else ?
}

How can I make my buttons - of a background color and text color that I don't know, but the button does - have that "disabled look" ?

(Note - the color update works on disabled items too - that is not really complicated though - whatever style sheet I apply on setting widget disabled can be applied in the colorUpdate function).

I just don't know how to apply a stylesheet with that gray shade - or possibly have a "disabled" option in the stylesheet even...
What do colors look like in "disabled" ?

1

There are 1 answers

2
ymoreau On BEST ANSWER

To set your own style for the disable state. You can set a special style for disabled state in the stylesheet :

m_colorButton->setStyleSheet(":enabled { color: " + foreground 
                             + "; background-color: " + color 
                             + " } :disabled { color: " + disabledForeground 
                             + "; background-color: " + disabledColor + " }");

edit: changed code for the widget instead of a global stylesheet.


To keep the default disabled style. You can set your custom style only for the enabled state, then when the widget is disabled the style does not apply :

m_colorButton->setStyleSheet(":enabled { color: " + foreground 
                             + "; background-color: " + color + "}");