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

相关推荐
卷无止境2 天前
C++ 的Eigen 库全解析
c++
卷无止境2 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴2 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
Quz3 天前
QML Hello World 入门示例
qt
博客18004 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴4 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨4 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
xcyxiner6 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner6 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner7 天前
DicomViewer (添加模型类)3
qt