样式表里有很多属性,例如
边框颜色 border-color、边框半径 border-radius、背景颜色 background-color、字体大小font-size: 等等
实际上,对于我们自定义的控件类,新增的属性值,也可以支持样式表:
直接上例子:
#include <QPushButton>
class CustomButton
: public QPushButton
{
Q_OBJECT
//添加一个自定义属性,名字为borderColor
Q_PROPERTY(QColor borderColor READ GetBorderColor WRITE SetBorderColor)
public:
CustomButton(QWidget *parent = nullptr);
virtual ~CustomButton();
QColor GetBorderColor() const;
void SetBorderColor(const QColor& color);
protected:
virtual void paintEvent(QPaintEvent* event) override;
private:
QColor m_borderColor;
};
#include "CustomButton.h"
#include <QDebug>
CustomButton::CustomButton(QWidget *parent)
: QPushButton(parent)
{
}
CustomButton::~CustomButton()
{
}
QColor CustomButton::GetBorderColor() const
{
return m_borderColor;
}
void CustomButton::SetBorderColor(const QColor& color)
{
//样式表中设置的属性值,会在这里被加载,其他成员函数读取m_borderColor就可以获得样式表中设置的值
m_borderColor = color;
}
void CustomButton::paintEvent(QPaintEvent* event)
{
QPushButton::paintEvent(event);
//接下来就可以读取m_borderColor的值,来绘制一些你想要绘制的图形了
}
对应的样式表内容为:
CustomButton {
qproperty-borderColor: red;
/*qproperty-borderColor: #FF0000;*/
}
C++中自定义的属性borderColor,在qss中对应的名字为:qproperty-borderColor。冒号后面的值对应为该属性的值,他会被传递进C++代码中。
--------分割线-------------------------------------------------------------------------------------------------------
以上代码演示了C++如何获取样式表中自定义的属性值,那么对于QT内置的一些属性,C++如何获取QSS中定义的值呢?
先上答案:有些属性值可以读到,有些被QT给private了,读不到。
对于被private的属性值,可以通过QMetaObject::invokeMethod来强行读出来,但是这违背了QT/C++的设计理念。不推荐。
下面演示C++如何读取QT公开的qss属性值。
首先是QSS示例文件:
MyWidget
{
background-color: red;/*背景色*/
color: white; /*文字色*/
}
MyWidget:hover
{
background-color: green; /*鼠标悬停色*/
}
void MyWidget::paintEvent(QPaintEvent *event)
{
QStyleOption opt;
opt.initFrom(this);//读取qss设置的样式
QPainter p(this);
//按照qss的设置来绘制widget
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
QPalette pal = opt.palette;
//读背景色,会读到red
QBrush backgroundBrush = pal.brush(QPalette::Background);
//读文字颜色,会读到white
QColor textColor = pal.color(QPalette::Text);
//读鼠标悬停时的背景色,会读到green
QBrush hoverBrush = pal.brush(QPalette::Highlight);
// 判断该控件上是否被鼠标悬停
if (opt.state & QStyle::State_MouseOver) {
backgroundBrush = hoverBrush;
textColor = hoverBrush.color();
}
//下面根据读到的qss值,随意绘制你想要的图形
painter.fillRect(rect(), backgroundBrush);
painter.setPen(textColor);
painter.drawText(rect(), Qt::AlignCenter, tr("Hello, World!"));
}