作者: 使徒保罗
声明: 欢迎交流学习,如有任何疑问,请通过邮箱联系本人
应用场景: 用户头像用圆形控件加载,需要任意变换尺寸,等比缩放头像图片并单击控件可以弹框设置头像
自定义label功能:
1.鼠标移动到label铺透明效果图
2.捕获鼠标单击消息,提交信号,模仿按钮的单击消息,完成按钮功能
核心代码:
#ifndef ROUNDLABEL_H
#define ROUNDLABEL_H
#include <QLabel>
class CRoundLabel:public QLabel
{
Q_OBJECT
public:
CRoundLabel(QWidget* parent=0);
signals:
void sigClick();
protected:
void paintEvent(QPaintEvent *e);
void enterEvent(QEvent* event);
void leaveEvent(QEvent *event);
void mousePressEvent(QMouseEvent *ev);
private:
bool m_bTransLayer; //透明层
};
#endif
#include "RoundLabel.h"
#include <QPainter>
CRoundLabel::CRoundLabel(QWidget *parent):QLabel(parent)
{
m_bTransLayer = false;
}
void CRoundLabel::paintEvent(QPaintEvent *e)
{
if(NULL != pixmap())
{
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
QPainterPath path;
int round = qMin(width(), height());
path.addEllipse(0, 0, round, round);
painter.setClipPath(path);
painter.drawPixmap(-1, -1, width()+2, height()+2, *pixmap());
if(m_bTransLayer)
{
//鼠标在label上,加载透明图片
QPixmap pixMap(":/user_change.png");
painter.drawPixmap(-1, -1, width()+2, height()+2, pixMap);
}
}
else
{
QLabel::paintEvent(e);
}
}
void CRoundLabel::enterEvent(QEvent *event)
{
m_bTransLayer = true;
update();//刷新label
}
void CRoundLabel::leaveEvent(QEvent *event)
{
m_bTransLayer = false;
update();//刷新label
}
void CRoundLabel::mousePressEvent(QMouseEvent *ev)
{ //鼠标单击消息
emit sigClick();
}
//调用方法
m_pCRoundLable = new CRoundLabel(this);
QPixmap pixMap(":/user.png");
m_pCRoundLable->setPixmap(pixMap);//初始化一个默认图片,可按需要调用这个接口改变label的图片m_pCRoundLable->setGeometry(10, 10, 80, 80);
初始化效果图: 鼠标移动到其上的效果图: