上一篇文章,需要自定义类,本文使用样式设置按下和松开的背景颜色。
1.头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
//#include "CustomButton.h"
#include <QVBoxLayout>
//#include <QLinearGradient>
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;
};
#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);//指定布局属于啥组件
QPushButton *button2=new QPushButton(this) ;
button2->setStyleSheet("background-color:#dddddd");//初始背景颜色
QObject::connect(button2, &QPushButton::pressed,
[button2]()//lambda函数
{
//qDebug("pressed!");
button2->setStyleSheet("background-color:#00ff00");
});
QObject::connect(button2, &QPushButton::released,
[button2]()//lambda函数
{ button2->setStyleSheet("background-color:#eeeeee");
//qDebug("released!");
});
this->setLayout(mainlayout);
}