Bollos00
Bollos00

Reputation: 49

Changing Background color of QCheckBox

I want to have a checkbox with the following style:

For that purpose I have created the follow stylesheet:

QCheckBox { background-color : cyan; }
QCheckBox::indicator { width : 20px; height : 20px; }

sadly the result was not was I expected, here is what I get:

enter image description here

But I want to have all background with the color cyan. I have checked the Qt Documentation About StyleSheet and have also also checked some old questions, but none of the has served me. When I added QCheckBox::indicator{ background-color : cyan; } the button became all cyan (like on the first image on the state unchecked) on checked and unchecked states. Neither adding other proprieties like border helped me.

I also tried to use QPalette instead, but never changed.

Here is my code:

    QWidget* w = new QWidget();

    QCheckBox* cb = new QCheckBox(w);

    cb->setFixedSize(20, 20);
    cb->setStyleSheet(QString("QCheckBox { background-color : cyan; }") + '\n' +
                      "QCheckBox::indicator { width : 20px; height : 20px; border : }");
    w->show();

EDIT 28/09/2020

I have recently figured out that the style of the application has influence on it. I was using the Breeze style, changing to Fusion style made it work as expected. The only problem is that it requires change the theme of the application itself. Anyway, here is the code sample in case it helps anyone:

#include <QApplication>
#include <QWidget>
#include <QCheckBox>


int main(int argc, char** argv)
{
    QApplication a(argc, argv);
    qApp->setStyle(QStyleFactory::create("Fusion"));
    QWidget* w = new QWidget();

    QCheckBox* cb = new QCheckBox(w);

    cb->setFixedSize(20, 20);
    cb->setStyleSheet(QString("QCheckBox { background-color : cyan; }") + '\n' +
                      "QCheckBox::indicator { width : 20px; height : 20px; border : }");
    w->show();
}

Upvotes: 2

Views: 5272

Answers (2)

Jens
Jens

Reputation: 6329

Probably

QCheckBox::indicator:unchecked {background-color : cyan;});

is what you wanted to see.

Edit: Too late

Upvotes: 1

Bollos00
Bollos00

Reputation: 49

I did not solve my problem using the stylesheet commands, I actually think that it is not possible SOURCE.

Anyway, I was I able to achieve my goals using one image for the checked state and another one for the unchecked state as follow.

    QWidget* w = new QWidget();

    QCheckBox* cb = new QCheckBox(w);

    cb->setFixedSize(20, 20);
    cb->setStyleSheet("QCheckBox::indicator { width : 20; height : 20; }\n"
                      "QCheckBox::indicator::unchecked { image : url(/path/**/unchecked.png); }\n"
                      "QCheckBox::indicator::checked { image : url(/path/**/checked.png); }");
    w->show();

Upvotes: 1

Related Questions