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);

}

//效果,两种状态的渐变色效果如下

off on

相关推荐
王老师青少年编程3 小时前
2025年【江苏“信息与未来”编程思维】真题及题解(T2:坐标变换)
c++·题解·真题·坐标变换·编程思维·江苏·信息与未来
西门吹-禅6 小时前
java springboot N+1问题
java·开发语言·spring boot
skywalk81636 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程
2023自学中7 小时前
C++ 内存追踪器
linux·c++
IT笔记8 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
2zcode8 小时前
免费开源项目文档:基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn
逝水无殇8 小时前
C# 运算符重载详解
开发语言·后端·c#
TPBoreas9 小时前
配置信息防泄露方案:.env 环境隔离详解(dotenv-java)
java·开发语言
敲代码的嘎仔9 小时前
实习日志day6--实习日志day6--title命名规范化&businessType纠正&补充缺失的@Log注解&报警与通信模块补充&产出阶段总结文档
java·开发语言·人工智能·git·python·实习·大二
江华森9 小时前
Python 实现高德地图找房(一):环境搭建与数据爬虫
开发语言·爬虫·python