QT c++ 自定义按钮类 加载图片 美化按钮

如果你有需要利用图片美化按钮的情况,本文能帮助你。

鼠标左键按下按钮和松开,按钮显示不同的图片。

1.按钮类

//因为此类比较简单,1个头文件搞定,没有cpp文件

#ifndef CUSTOMBUTTON_H

#define CUSTOMBUTTON_H

#include <QPushButton>
#include <QPainter>
#include <QMouseEvent>
#include <QPixmap>

class CustomButton : public QPushButton

{

Q_OBJECT

public:

CustomButton(QWidget *parent = nullptr) : QPushButton(parent) {}

bool pressed1;

protected:

void paintEvent(QPaintEvent *event) override

{

QPainter painter(this);

QPixmap pixmap;

//if (isDown()) {//这个不起作用

if (pressed1==true)//自己定义了个按下的布尔变量

{

pixmap.load("d:/Pictures/button_forward_2.png"); // 按下时的图片路径,改成你自己的

qDebug()<<"press";

}

else

{

pixmap.load("d:/Pictures/button_forword_1.png"); // 释放时的图片路径

qDebug()<<"release";

}

painter.drawPixmap (rect(), pixmap);

}

void mousePressEvent(QMouseEvent *event) override

{ pressed1=true;

update(); // 按下时重绘按钮

//qDebug()<<"_press";

}

void mouseReleaseEvent(QMouseEvent *event) override

{ pressed1=false;

update(); // 释放时重绘按钮

//qDebug()<<"_release";

}

};

#endif // CUSTOMBUTTON_H

2.widget调用 CustomButton类

(1)头文件

#define WIDGET_H

#include <QWidget>
#include "CustomButton.h"
#include <QVBoxLayout>

QT_BEGIN_NAMESPACE

namespace Ui {

class Widget;

}

QT_END_NAMESPACE

class Widget : public QWidget

{

Q_OBJECT

public:

Widget(QWidget *parent = nullptr);

~Widget();

voidinitUI();

private:

Ui::Widget *ui;

CustomButton *button;

};

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

CustomButton *button=new CustomButton(this) ;
button->setFixedWidth(55);
button->setFixedHeight(30);

mainlayout->addWidget(button);//指定布局包含啥组件

this->setLayout(mainlayout);

}

相关推荐
ShineWinsu21 小时前
对于Qt:事件分发器以及事件过滤器的解析
c++·qt·面试·gui·客户端·事件过滤器·事件分发器
ShineWinsu2 天前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
西西弗Sisyphus2 天前
Qt QML 程序是怎么跑起来的(1)qml-only
开发语言·c++·qt
小灰灰搞电子2 天前
QAccel 类讲解与代码示例:Qt 3 中的键盘加速键管理
qt·计算机外设
ShineWinsu3 天前
对于Qt:重写事件步骤的解析
开发语言·c++·qt·客户端·事件·鼠标事件·步骤
敲上瘾4 天前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
ShineWinsu4 天前
对于Qt:QFontDialog的解析
c++·qt·面试·gui·字体·客户端·qfontdialog
JosieBook4 天前
【鸿蒙】把一个 Qt 桌面视频编辑器“搬“上鸿蒙 PC:Olive 移植适配全记录
qt·音视频·harmonyos
Lucas. Wáng5 天前
Qt学习之旅
c++·qt
金色熊族6 天前
qt5.15.9编译qt-creator7.0.2源码
linux·qt