1、对于同一个部件来说,只有最后一个setStyleSheet起作用(覆盖前面的设置),所以如果对组件设置样式,一次性全部设置完成
btn1->setStyleSheet("QPushButton{color:red}"); //设定前景颜色,就是字体颜色
btn1->setStyleSheet("QPushButton{background:yellow}"); //设定背景颜色为红色
//上面两句执行完毕后,btn1只修改了背景色为红色
btn1->setStyleSheet("QPushButton{color:red;background:yellow}");
//这句执行完毕,才是既修改字体颜色,也修改背景色
2、按钮的三种状态
未处于特殊状态、悬停、点击
btn1->setStyleSheet("QPushButton{color:red;background:yellow}"
"QPushButton::hover{background:rgb(110,115,100);}"
"QPushButton::pressed{background:#eb7350;}");
3、设置按钮的边框样式
4、自定义按钮类 --- 继承QPushButton,上图下字。 悬停时改变图案和文字的颜色
使用paintEvent绘制(不推荐)
class myButton : public QPushButton
{
Q_OBJECT
public:
explicit ZUtilityBtn(QWidget *parent = nullptr);
void setText(const QString &text);
void setIcon(const QString &icon, const QString &iconHover);
protected:
void paintEvent(QPaintEvent *event) override;
private:
QString m_text;
QImage m_icon_nor; //正常时的图案
QImage m_icon_hover; //悬停时的图案
};
void myButton::setIcon(const QString &icon, const QString &iconHover)
{
m_icon_nor = QImage(icon);
m_icon_hover = QImage(iconHover);
}
void myButton::setText(const QString &text)
{
m_text = text;
}
void myButton paintEvent(QPaintEvent *event)
{
QPainter painter(this);
//设置抗锯齿 、平滑转换
p.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform|QPainter::TextAntialiasing);
QRect rect(0,0,this->width(),this->height());
int margin_h = 0.1 * this->height();
int margin_w = 0.1 * this->width();
int baseSize = qMin(this->width(),this->height());
qreal radius = baseSize * 0.06;
painter.setBrush(QColor::rgb());
painter.drawRoundRect(rect,radius ,radius);
}
5、完全通过setStyleSheet将按钮设置为上图下文字形式
QPushButton{ border: 1px solid #cccccc; color:black; font-size:20px; border-radius:10px; padding: 2px 2px 0px 4px; text-align:bottom; background-repeat: no-repeat; background-position: top; background-origin:content; background-color:rgb(235,246,248); background-image: url(":/set_gray.png"); }
6、在Qt样式表(QSS)中,可以通过类名或者对象名来区分不同的控件并应用不同设置
下方举例,两个自定义按钮,需要显示的图片不同。同时,每个按钮自身悬停时图片也要切换。下面的方式可以尽可能减少冗余代码
static const QString BtnRight = "ZMainRightBtn{"
"border: none;"
"color:black; "
"font-size:20px;"
"padding: 2px 2px 4px 4px;"
"text-align:bottom;"
"background-repeat: no-repeat;"
"background-position: top;"
"background-origin:content;"
"background-color:rgb(235,246,248);"
"}"
"ZMainRightBtn:hover{"
"color:rgb(60,95,232);"
"}"
"ZMainRightBtn#rPBtn01{"
"background-image: url(:/res/image/set_gray.png);"
"}"
"ZMainRightBtn#rPBtn01:hover{"
"background-image: url(:/res/image/set_blue.png);"
"}"
"ZMainRightBtn#rPBtn02{"
"background-image: url(:/res/image/manage_gray.png);"
"}"
"ZMainRightBtn#rPBtn02:hover{"
"background-image: url(:/res/image/manage_blue.png);"
"}";
常见问题:
当给控件使用setStyleSheet失效时,需要检查几个方面
1、首先肯定时进行设置的QSS字符串有没有语法或者拼写上的错误2、有没有在ui界面已经对该控件进行样式的设置
如果在这里进行了样式的设置,那在代码上再进行设置样式,是不起作用的
3、检查已完成的样式设置和当前是否有冲突
4、部分QSS设置和paintEvent会有冲突