Qt 样式与 QLinearGradient 渐变详解

日期:2025-12-10
分类:Qt / C++ / 界面美化
标签:QLinearGradient、Qt样式表、QSS、渐变效果


🌈 一、QLinearGradient 是什么?

Qt 中,QLinearGradient 是用于绘制 线性渐变(Linear Gradient) 的类。
它可以让颜色沿一条直线平滑过渡,常用于:

  • 自定义控件绘图(通过 QPainter
  • Qt 样式表(QSS)背景渐变
  • 绘制按钮、标题栏、图表等 UI 效果

🧱 二、基本原理

线性渐变由以下部分组成:

  • 起点 (start):渐变开始的坐标
  • 终点 (end):渐变结束的坐标
  • 颜色停靠点 (color stop):颜色变化的位置(0.0~1.0)

颜色在这些停靠点之间平滑过渡。


🎨 三、QPainter 中使用示例

#include <QPainter>
#include <QLinearGradient>

void MyWidget::paintEvent(QPaintEvent *) {
    QPainter painter(this);

    // 创建渐变:从左上角到右下角
    QLinearGradient gradient(0, 0, width(), height());

    // 定义颜色停靠点
    gradient.setColorAt(0.0, Qt::red);
    gradient.setColorAt(0.5, Qt::yellow);
    gradient.setColorAt(1.0, Qt::green);

    // 应用渐变画刷
    painter.setBrush(gradient);
    painter.setPen(Qt::NoPen);
    painter.drawRect(rect());
}

🧩 参数说明

方法 说明
QLinearGradient(x1, y1, x2, y2) 起点与终点坐标
setColorAt(pos, color) 设置渐变颜色(pos ∈ [0,1])
setSpread(QGradient::Spread) 设置超出区域的填充模式

🪄 四、Spread 模式

控制渐变在边界外的延伸方式:

模式 效果说明
PadSpread(默认) 使用最后一个颜色填充外部区域
RepeatSpread 重复整个渐变
ReflectSpread 反射式重复渐变

示例:

gradient.setSpread(QGradient::ReflectSpread);

🧁 五、QSS(样式表)中的线性渐变

Qt 样式表支持直接使用 qlineargradient() 定义背景:

QPushButton {
    border: 1px solid #888;
    border-radius: 6px;
    color: white;
    background: qlineargradient(
        x1:0, y1:0, x2:0, y2:1,       /* 从上到下 */
        stop:0 #4A90E2,               /* 顶部颜色 */
        stop:0.5 #357ABD,             /* 中间颜色 */
        stop:1 #2C5AA0                /* 底部颜色 */
    );
}

📐 坐标说明

参数 说明
x1, y1 渐变起点(相对控件)
x2, y2 渐变终点(相对控件)
stop 渐变停靠点及颜色

例如:

  • x1:0, y1:0, x2:0, y2:1 → 垂直渐变
  • x1:0, y1:0, x2:1, y2:0 → 水平渐变

💡 六、QSS 动态效果示例

按钮悬停时渐变变化:

QPushButton {
    color: white;
    border-radius: 5px;
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
        stop:0 #6EA3F2, stop:1 #2E6BD1);
}

QPushButton:hover {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
        stop:0 #7FB6FF, stop:1 #3B82F6);
}

🧠 七、与透明度结合使用

可使用带透明度的 QColor 生成光泽或阴影:

gradient.setColorAt(0, QColor(255, 255, 255, 180));
gradient.setColorAt(1, QColor(0, 0, 0, 80));

效果:上亮下暗,常用于立体按钮、气泡、卡片等。


🧩 八、其他渐变类型对比

类型 特点
QLinearGradient 线性渐变 沿直线方向变化
QRadialGradient 放射渐变 从中心向外扩散
QConicalGradient 圆锥渐变 围绕中心旋转变化

🖼 九、渐变方向示意

方向 参数 效果
从上到下 x1:0, y1:0, x2:0, y2:1 垂直渐变
从左到右 x1:0, y1:0, x2:1, y2:0 水平渐变
左上 → 右下 x1:0, y1:0, x2:1, y2:1 对角线渐变

🚀 十、总结

  • QLinearGradient 可用于绘图和 QSS 样式美化。
  • 支持多颜色点、透明度、扩展模式。
  • 在 QSS 中可轻松实现渐变背景与交互效果。
  • 搭配动画可实现更动态的视觉体验。

💬 小结:
掌握 QLinearGradient,你就能轻松为 Qt 程序增加色彩层次感和高品质视觉效果。

推荐阅读:

posted @ 2025-12-10 15:37  nemosc  阅读(0)  评论(0)    收藏  举报