QT c++ 样式 设置 按钮(QPushButton)的渐变色美化

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

1.头文件

#ifndef WIDGET_H

#define WIDGET_H

#include <QWidget>

//#include "CustomButton.h"
#include <QVBoxLayout>
#include <QLinearGradient>
#include <QPushButton>

//#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() ;

//void setButton(QPushButton * button,int color,int width,int height);

private:

Ui::Widget *ui;

//CustomButton *button;

QPushButton *button2;

// QLabel *label;

// QTimer *timer;

//int counter=0;

bool flag_on=false;//on/off标志

};

#endif // WIDGET_H

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);//指定布局属于啥组件

setStyleSheet("background-color:rgb(160,203,254);");

QPushButton *button2=new QPushButton(this) ;

button2->setFixedWidth (65);

button2->setFixedHeight (33);

//button2->setStyleSheet("background-color:#dddddd");//初始背景颜色

//setButton(button2,4,65,33);

QObject::connect(button2, &QPushButton::pressed,

**button2,this**\]()//lambda函数 { **flag_on=!flag_on** ;**//状态取反** //qDebug("pressed!"); if(flag_on) { QString color_on= "border:1px solid gray;" "**background-color: qlineargradient**(x1: 0, y1: 0, x2: 0, y2: 1, " "**stop**: 0 #669066," "**stop**: 0.5 #43ff43," "**stop**: 1 #669066);"; //"background-color:#00ff73;";//上面几行是线性过渡色 button2-\>**setStyleSheet(color_on)**; //qDebug("On!"); } else { QString color_off= "border:1px solid gray;" "**background-color: qlineargradient**(x1: 0, y1: 0, x2:0, y2: 1, " "**stop**: 0.1 #aaaaaa," "**stop**: 0.5 #ffffff," "**stop**: 1 #cccccc);"; // "background-color:#f6f6f6;";//上面几行是线性过渡色 button2-\>**setStyleSheet(color_off)** ; //qDebug("Off!"); } }); mainlayout-\>addWidget(button2);//指定布局包含啥组件 this-\>setLayout(mainlayout); } //效果,两种状态的渐变色效果如下 ![](https://i-blog.csdnimg.cn/direct/0f1370654156432da3457cbf2302550d.png) ![](https://i-blog.csdnimg.cn/direct/617fba5688a6442fb321f8b09051ace2.png) off on

相关推荐
嵌入式-老费6 分钟前
Easyx图形库应用(和lua结合使用)
开发语言·lua
AsiaLYF7 分钟前
kotlin中MutableStateFlow和MutableSharedFlow的区别是什么?
android·开发语言·kotlin
Asuncion00718 分钟前
Docker核心揭秘:轻量级虚拟化的革命
服务器·开发语言·docker·云原生
深思慎考1 小时前
RabbitMQ 入门:基于 AMQP-CPP 的 C++ 实践指南与二次封装
开发语言·c++·分布式·rabbitmq·api
深思慎考1 小时前
Ubuntu 系统 RabbitMQ 安装指南与使用(含 C++ 客户端与 SSL 错误解决)
c++·ubuntu·rabbitmq·github·rabbitmqpp
catchadmin1 小时前
PHP8.5 的新 URI 扩展
开发语言·后端·php
似水流年 光阴已逝1 小时前
从Excel姓名匹配案例学Python:由点及面的系统化学习指南
开发语言·python·excel
重生之我要当java大帝1 小时前
java微服务-尚医通-管理平台前端搭建-医院设置管理-4
java·开发语言·前端
Q_Q19632884752 小时前
python+vue的在线租房 房屋租赁系统
开发语言·vue.js·spring boot·python·django·flask·node.js
草莓熊Lotso2 小时前
《C++ Web 自动化测试实战:常用函数全解析与场景化应用指南》
前端·c++·python·dubbo