QT c++ 样式 设置 标签(QLabel)的渐变色美化

上一篇文章中描述了按钮的纯色,本文描述标签的渐变色美化

1.头文件

#ifndef WIDGET_H

#define WIDGET_H

#include <QWidget>

//#include "CustomButton.h"
#include <QVBoxLayout>
#include <QLinearGradient>
#include <QLabel>
#include <QTimer>

QT_BEGIN_NAMESPACE

namespace Ui {

class Widget;

}

QT_END_NAMESPACE

class Widget : public QWidget

{

Q_OBJECT

public:

Widget(QWidget *parent = nullptr);

~Widget();

void initUI();

private:

Ui::Widget *ui;

// CustomButton *button;

// QPushButton *button2;

QLabel *label;

QTimer *timer;

int counter=0;//计时器

};

2.cpp文件

#include "widget.h"

#include "ui_widget.h"

Widget::Widget(QWidget *parent)

: QWidget(parent)

, ui(new Ui::Widget)

{

ui->setupUi(this);

initUI();

}

Widget::~Widget()

{

delete ui;

}

void Widget::initUI()

{

QVBoxLayout * mainlayout = new QVBoxLayout(this);//指定布局属于啥组件

QLabel *label=new QLabel(this);

timer=new QTimer(this);

timer->start(1000);//定时1秒

QObject::connect(timer, &QTimer::timeout,

**label,this**\]()//lambda函数 { **counter++** ; if(**1==counter%2** ) //qDebug("pressed!"); { label-\>setStyleSheet(" border-radius: 15px;" "border: 2px solid rgb(100, 120, 100); " "**background-color: qlineargradient**(x1: 0, y1: 0," " x2: 1, y2: 1, " "**stop**: 0 #ffffff," "**stop**: 0.3 #bbeebb," "**stop**: 1 #4f4f4f);" );//暗 } else { label-\>setStyleSheet(" border-radius: 15px;" "border: 2px solid rgb(100, 120, 100); " "**background-color: qlineargradient**(x1: 0, y1: 0, x2: 1, y2: 1, " "**stop**: 0 #ffffff," "**stop**: 0.3 #43ff43," "**stop**: 1 #669066);" );//亮绿色 } }); **label-\>setFixedWidth(30); label-\>setFixedHeight(30);** mainlayout-\>addWidget(label);//指定布局包含啥组件 this-\>setLayout(mainlayout); } //效果: ![](https://i-blog.csdnimg.cn/direct/b14806d003854380aaf04acf0980d106.png) ![](https://i-blog.csdnimg.cn/direct/46de3327eab54f21ad493ccd4c376c73.png)

相关推荐
крон2 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan3 小时前
c++ 单例模式
开发语言·c++·单例模式
老胖闲聊3 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1183 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之4 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?4 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头5 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
liuyang-neu5 小时前
java内存模型JMM
java·开发语言
利刃大大5 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
喜欢吃燃面5 小时前
C++刷题:日期模拟(1)
c++·学习·算法