改变 QCheckBox 的背景颜色

Changing Background color of QCheckBox

我想要一个具有以下样式的复选框:

为此,我创建了以下样式表:

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

遗憾的是结果不是我预期的,这是我得到的:

但我希望所有背景都为青色。 我检查了 Qt Documentation About StyleSheet 并且还检查了一些旧问题,但是 none 对我有用。当我添加 QCheckBox::indicator{ background-color : cyan; } 时,按钮在选中和未选中状态下变为全青色(就像在未选中状态的第一张图片上一样)。添加 border 等其他属性对我没有帮助。

我也尝试过使用 QPalette,但从未改变。

这是我的代码:

    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();

编辑 2020 年 9 月 28 日

我最近发现应用程序的样式对其有影响。我使用的是 Breeze 风格,更改为 Fusion 风格使其按预期工作。唯一的问题是它需要更改应用程序本身的主题。无论如何,这里是代码示例以防它对任何人有帮助:

#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();
}

我没有使用样式表命令解决我的问题,实际上我认为这是不可能的SOURCE

无论如何,我能够使用一张图片用于选中状态,另一张图片用于未选中状态来实现我的目标,如下所示。

    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();

可能

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

是你想看到的。

编辑:太晚了