Qt5 自绘按钮控件,实现高度个性化的功能。核心思想是重写paintEvent等各种事件处理函数,根据当前状态在QPaintDevice上绘制图像。
效果:
pic1
MPushButton.h
#ifndef MPUSHBUTTON_H
#define MPUSHBUTTON_H
#include <QPushButton>
#include <QLineEdit>
class MPushButton : public QPushButton
{
Q_OBJECT
public:
MPushButton(QWidget *parent = nullptr);
~MPushButton() override;
protected:
void paintEvent(QPaintEvent *event) override;
void enterEvent(QEvent *event) override;
void leaveEvent(QEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
bool isHover = false;
bool isPressed = false;
};
#endif // MPUSHBUTTON_H
MPushButton.cpp
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QColor>
#include <QRect>
#include <QDebug>
#include "MPushButton.h"
MPushButton::MPushButton(QWidget *parent)
: QPushButton(parent)
{
}
MPushButton::~MPushButton()
{
}
void MPushButton::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
QColor blue;
if (isHover)
blue.setRgb(93, 173, 226);
else
blue.setRgb(53, 152, 219);
if (isPressed)
blue.setRgb(46, 134, 193);
// draw background of the button
QBrush brush(blue);
painter.setPen(Qt::NoPen);
painter.setBrush(brush);
painter.drawRoundedRect(QRectF(0,0, this->width() , this->height()), 15, 15);
// draw text
painter.setPen(QPen(QColor(215, 219, 221)));
painter.setFont(font());
painter.drawText(rect(), Qt::AlignCenter, text());
}
void MPushButton::enterEvent(QEvent *event)
{
isHover = true;
QPushButton::enterEvent(event);
}
void MPushButton::leaveEvent(QEvent *event)
{
isHover = false;
QPushButton::leaveEvent(event);
}
void MPushButton::mousePressEvent(QMouseEvent *event)
{
isPressed = true;
QPushButton::mousePressEvent(event);
move(this->x(), this->y() + 5);
}
void MPushButton::mouseReleaseEvent(QMouseEvent *event)
{
isPressed = false;
QPushButton::mouseReleaseEvent(event);
move(this->x(), this->y() - 5);
}
网友评论