// .h文件
#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
//.cpp
#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(":/new/prefix/001.jpg");
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();
}
label我们已经重写了,那么究竟要怎么使用它呢?其实只需要在我们拖动的控件中,将其提升为我们所写的类就可以了,以下是详细操作: