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

相关推荐
ajassi20003 小时前
开源 C++ QT Widget 开发(十五)多媒体--音频播放
linux·c++·qt·开源
CodeCraft Studio4 小时前
PDF处理控件Aspose.PDF教程:使用 Python 将 PDF 转换为 Base64
开发语言·python·pdf·base64·aspose·aspose.pdf
零点零一4 小时前
VS+QT的编程开发工作:关于QT VS tools的使用 qt的官方帮助
开发语言·qt
鹅毛在路上了5 小时前
C++, ffmpeg, libavcodec-RTSP拉流,opencv实时预览
c++·opencv·ffmpeg
John_ToDebug6 小时前
定制 ResourceBundle 的实现与 DuiLib 思想在 Chromium 架构下的应用解析
c++·chrome·ui
lingchen19066 小时前
MATLAB的数值计算(三)曲线拟合与插值
开发语言·matlab
gb42152876 小时前
java中将租户ID包装为JSQLParser的StringValue表达式对象,JSQLParser指的是?
java·开发语言·python
一朵梨花压海棠go6 小时前
html+js实现表格本地筛选
开发语言·javascript·html·ecmascript
蒋星熠6 小时前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
翻滚丷大头鱼7 小时前
Java 集合Collection—List
java·开发语言