目录
0.简介
**
QLinearGradient
**是 Qt 框架中的一个类,用于定义线性渐变效果(通过样式表设置)。它可以用来填充形状、背景或其他图形元素,创建从一个颜色到另一个颜色的平滑过渡效果。
先看下实现效果(我用了一个label控件承接,一个从浅灰到深灰的渐变,带50的圆角)
1)qtDesigner中
2)实际执行

想要彩色?满足你

1.功能详述
1)首先我们看下用样式是如何设置的(以下均已彩色图的颜色为准)

cpp
ui->label->setStyleSheet("background:qlineargradient(x1:1, y1:0, x2:0, y2:1, stop:0.0 red, stop:0.5 green, stop:1 blue);"
"border-radius:50px;");
重点就是这一句代码,设置样式。
通过给label设置一个背景颜色,再加一个border-radius的圆角即可实现,重点是qlineargradient的参数,我们来分析下:
cpp
qlineargradient(x1:1, y1:0, x2:0, y2:1, stop:0.0 red, stop:0.5 green, stop:1 blue)
别看参数这么多,分组看就好了,一共有5个组:

a)起始点坐标(x1,y1)
b)结束点坐标(x2,y2)
c)起始点颜色和开始点(stop:0.0 red)
d)中间段颜色和中间点(stop:0.5 green)
e)结束点颜色和结束点(stop:1 blue)
(参考图)
|---------------------------|-------------------------------------------------------------------------------------------------------------------------------------|
| 参数 | 含义 |
| qlineargradient(...) | 设置背景为线性渐变 |
| x1:1, y1:0(x1,y1要一起看) | 渐变起点的坐标(看上面的参考图中的红色坐标,仅看四个点坐标) 也就是颜色从(1,0)开始,也就是右上角 * x1:1
表示起点的水平位置为 1(相对于元素的宽度,1 表示最右侧) * y1:0
表示起点的垂直位置为 0(相对于元素的高度,0 表示最顶部) |
| x2:0, y2:1(x2,y2要一起看) | 渐变终点的坐标(看上面的参考图的红色坐标) 也就是颜色到(0,1)结束,也就是左下角 * x2:0
表示终点的水平位置为 0(最左侧) * y2:1
表示终点的垂直位置为 1(最底部) |
| stop:0.0 red | 在渐变线的起点(位置 0.0)设置颜色为红色,参考上图的橙色数字位置 |
| stop:0.5 green | 在渐变线的中间点(位置 0.5)设置颜色为绿色,参考上图的橙色数字位置 |
| stop:1 blue | 在渐变线的终点(位置 1.0)设置颜色为蓝色,参考上图的橙色数字位置 |
也就是先看起点终点,再看颜色。
如上述代码样式可简述为:从右上到左下,分别是红、绿、蓝三个颜色。
3.举一反三的样式
1)如果要调换开始和结束的颜色(红蓝调换),有两种方式:
i)调换起始点:
(x1,y1),原(1,0)变为(0,1)+ (x2,y2),原(0,1)变为(1,0)

ii)调换起点(red)和终点(blue)的颜色

2)我想让红色少一点
第二段stop的值少一点,意思是绿色的中心点是0.2

cpp
// ui->label->setStyleSheet("background:qlineargradient(x1:1, y1:0, x2:0, y2:1, stop:0.0 red, stop:0.5 green, stop:1 blue);"
ui->label->setStyleSheet("background:qlineargradient(x1:1, y1:0, x2:0, y2:1, stop:0.0 red, stop:0.2 green, stop:1 blue);"
"border-radius:50px;");
3)如果我只想要两个颜色,不想要中间的绿色了
去掉第二段stop参数(, stop:0.5 green)即可

cpp
// ui->label->setStyleSheet("background:qlineargradient(x1:1, y1:0, x2:0, y2:1, stop:0.0 red, stop:0.5 green, stop:1 blue);"
ui->label->setStyleSheet("background:qlineargradient(x1:1, y1:0, x2:0, y2:1, stop:0.0 red,stop:1 blue);"
"border-radius:50px;");
大家可自行发挥想象力,可以创造出很多样式
--END--