简体   繁体   English

更改QCheckBox文本颜色

[英]Changing QCheckBox text color

I found the same question there: how to change QCheckBox text label color in Qt? 我在那里发现了同样的问题: 如何在Qt中更改QCheckBox文本标签颜色?

But unfortunately, none of it work for me on a mac. 但不幸的是,它在Mac上对我没有任何作用。

On Linux and Windows, by default the text of a QWidget (QLabel, QCheckBox, QRadioButton) is white. 在Linux和Windows上,默认情况下,QWidget(QLabel,QCheckBox,QRadioButton)的文本为白色。 On the mac, it's black. 在Mac上,它是黑色的。 Unfortunately this cause issues in my screen as the text is unreadable (I have black background).. 不幸的是,这导致我的屏幕出现问题,因为文字不可读(我有黑色背景)..

I have derived the QCheckBox class so in the constructor you get: 我已经导出了QCheckBox类,所以在你得到的构造函数中:

class MPUBLIC MythCheckBox: public QCheckBox
{
    Q_OBJECT

  public:
    MythCheckBox(QWidget *parent = 0, const char *name = "MythCheckBox")
        : QCheckBox(parent)
    {
        setObjectName(name);
#ifdef Q_OS_MAC
//        setStyleSheet("QCheckBox { color : white; }; QCheckBox::indicator { color:black; }");
        QPalette p = palette();
        p.setColor(QPalette::WindowText, Qt::white);
        setPalette(p);
#endif
    };

If I use stylesheets like: 如果我使用样式表,如:

setStyleSheet("QCheckBox { color : white; }; QCheckBox::indicator { color:black; }");

then my text is white as I want, but the checkmark itself becomes invisible... 那么我的文字就像我想要的那样是白色的,但是勾选标记本身变得不可见......

If I use the 2nd method: 如果我使用第二种方法:

QPalette p = palette();
p.setColor(QPalette::WindowText, Qt::white);
setPalette(p);

The checkbox text does become white, and the checkmark itself is still black, it looks like it works. 复选框文本变为白色,复选标记本身仍为黑色,看起来像是有效的。 But if I ever move the focus to the QCheckBox, the text becomes black again, and it will remain black forever. 但是,如果我将焦点移动到QCheckBox,文本将再次变为黑色,并且它将永远保持黑色。

I tried also: 我也尝试过:

QPalette p = palette();
p.setColor(QPalette::Active, QPalette::WindowText, Qt::white);
p.setColor(QPalette::Inactive, QPalette::WindowText, Qt::white);
setPalette(p);

Mind you, I only get this weird behavior on the mac; 请注意,我只能在mac上获得这种奇怪的行为; if I try the same code in Linux (with different colors like red), then everything behaves like I want it to. 如果我在Linux中尝试相同的代码(使用不同的颜色,如红色),那么一切都表现得像我想要的那样。

Any ideas on how to change the color of a QCheckBox's text, and only the text? 有关如何更改QCheckBox文本颜色以及仅文本的任何想法?

For some widgets you have to disable a native look (appearance). 对于某些小部件,您必须禁用本机外观(外观)。 For example QPushButton ( http://doc.qt.io/qt-4.8/stylesheet-reference.html ). 例如QPushButton( http://doc.qt.io/qt-4.8/stylesheet-reference.html )。 So, for checkbox you can try to set borders. 因此,对于复选框,您可以尝试设置边框。 So checkbox's style looks like: 所以复选框的样式如下:

QCheckBox {
   border: none;
   color: white;
}

Works for me. 适合我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM