# 设置控件颜色 ## 一、使用QPalette设置颜色 ```c++ QPalette pale; pale.setColor(QPalette::Background,Qt::black); // 将背景色设置为black this->setPalette(pale); ``` ![1559129226675](assets/1559129226675.png) 有些人[设置背景色](https://blog.csdn.net/qq_40388909/article/details/79460175)时这样设置: ```c++ QPalette palette(this->palette()); palette.setColor(QPalette::Background, Qt::black); this->setPalette(palette); ``` ​ 在``setPalette`之前和之后分别调用一次`palette()`调试如下: ```c++ QPalette pale; qDebug()<palette(); pale.setColor(QPalette::Background,Qt::black); this->setPalette(pale); qDebug()<palette(); ``` ​ 输出结果如下: > QPalette(resolve=0x0,) > > QPalette(resolve=0x400,,Window:[Active:0xff000000,Disabled:0xff000000,Inactive:0xff000000]) 可以看到,这样做完全没有必要。 > 看起来pale是栈对象,在退出构造函数时会被析构,但是经过测试,并不是这样的,Qt会自动保存它,你不用担心它的生存周期。 # 二、使用QSS设置背景色 ```c++ this->setStyleSheet(R"( BackColor{ background-color:black; } )"); ``` ​ 其中,`BackColor`是你的类名。 ![1559129187647](assets/1559129187647.png) > 由于子控件会继承父控件的QSS,因此,并不建议使用QSS设置背景色。