自定义label头文件
#ifndef MYLABEL_H
#define MYLABEL_H
#include <QWidget>
#include <QLabel>
#include <QMoveEvent>
#include <QEvent>
#include <QMouseEvent>
#include <QPoint>
#include <QDebug>
#include <QTimer>
class MyLabel : public QLabel
{
Q_OBJECT
public:
explicit MyLabel(QWidget *parent = nullptr);
signals:
protected:
void mousePressEvent(QMouseEvent *ev);
void mouseMoveEvent(QMouseEvent *ev);
void mouseReleaseEvent(QMouseEvent *ev);
public slots:
void msgCountAdd();
void msgAdd();
void msgSub();
private:
QPoint dragPosition;
QWidget *m_pParent;
int m_nMovePointX;
int m_nMovePointY;
QTimer *m_pTimer;
int m_nMsgCount;
};
#endif // MYLABEL_H
自定义label源文件
#include "Mylabel.h"
MyLabel::MyLabel(QWidget *parent) : QLabel(parent), m_nMsgCount(0), m_pParent(parent)
{
const QString labelStyleStr = "min-width: 32px; min-height: 32px;border-radius: 16px; border:2px solid yellow;background:red;color:white;font:14pt 微软雅黑";
setStyleSheet(labelStyleStr);
setAlignment(Qt::AlignCenter);
m_pTimer = new QTimer;
connect(m_pTimer,&QTimer::timeout,this,&MyLabel::msgCountAdd);
//m_pTimer->start(300);
}
void MyLabel::mousePressEvent(QMouseEvent *ev)
{
if(ev->button() == Qt::LeftButton)
{
dragPosition = ev->globalPos()-frameGeometry().topLeft();
ev->accept();
}
}
void MyLabel::mouseMoveEvent(QMouseEvent *ev)
{
if(ev->buttons() & Qt::LeftButton)
{
qDebug() << ev->globalPos()- dragPosition;
m_nMovePointX = (ev->globalPos()- dragPosition).x();
m_nMovePointY = (ev->globalPos()- dragPosition).y();
if(m_nMovePointX < 0 || m_nMovePointY < 0 || m_nMovePointY > m_pParent->rect().bottom() - this->rect().width() || m_nMovePointX > m_pParent->rect().right() - this->rect().width())
{
//防止移出顶部和底部
if(m_nMovePointY > m_pParent->rect().bottom() - this->rect().width() || m_nMovePointY < 0)
{
move((ev->globalPos() - dragPosition).x(), this->geometry().y());
}
//防止移出左侧和右侧
if(m_nMovePointX > m_pParent->rect().right() - this->rect().width() || m_nMovePointX < 0)
{
move(this->geometry().x(),(ev->globalPos() - dragPosition).y());
}
//防止移出左上角
if(m_nMovePointX < 0 && m_nMovePointY < 0)
{
move(0,0);
}
//防止移出右小角
if(m_nMovePointY > m_pParent->rect().bottom() - this->rect().width() && m_nMovePointX > m_pParent->rect().right() - this->rect().width())
{
move(m_pParent->rect().right() - this->rect().width(), m_pParent->rect().bottom() - this->rect().height());
}
//防止移出右上角
if(m_nMovePointY < 0 && m_nMovePointX > m_pParent->rect().right() - this->rect().width())
{
move(m_pParent->rect().right() - this->rect().width(),0);
}
//防止移出左上角
if(m_nMovePointX < 0 && m_nMovePointY > m_pParent->rect().bottom() - this->rect().height())
{
move(0,m_pParent->rect().bottom() - this->rect().height());
}
}
else
{
move(ev->globalPos() - dragPosition);
}
}
}
效果: