- 鼠标进入:enterEvent
- 鼠标离开:leaveEvent
- 鼠标按下:mousePressEvent
- 鼠标释放:mouseRelaseEvent
- 鼠标移动:mouseMoveEvent
提升为自定义控件MyLabel
代码:
//mylabel.h
#ifndef MYLABEL_H
#define MYLABEL_H
#include <QLabel>
class MyLabel : public QLabel
{
Q_OBJECT
public:
explicit MyLabel(QWidget *parent = 0);
//鼠标进入
void enterEvent(QEvent *);
//鼠标离开
void leaveEvent(QEvent *);
//鼠标按下
void mousePressEvent(QMouseEvent *ev);
//鼠标释放
void mouseReleaseEvent(QMouseEvent *ev);
//鼠标移动
void mouseMoveEvent(QMouseEvent *ev);
signals:
public slots:
};
#endif // MYLABEL_H
//mylabel.cpp
#include "mylabel.h"
#include "QDebug"
#include "QMouseEvent"
MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
{
//设置鼠标追踪
// this->setMouseTracking(true);
}
//鼠标进入
void MyLabel::enterEvent(QEvent *){
qDebug()<<"鼠标进入";
}
//鼠标离开
void MyLabel::leaveEvent(QEvent *){
qDebug()<<"鼠标离开";
}
//鼠标按下
void MyLabel::mousePressEvent(QMouseEvent *ev){
//如果是鼠标左键按下,才打印信息
if(ev->button() == Qt::LeftButton){
//字符串格式化
QString str = QString("鼠标按下: x= %1 , y= %2").arg(ev->x()).arg(ev->y());
qDebug()<<str;
}
}
//鼠标释放
void MyLabel::mouseReleaseEvent(QMouseEvent *ev){
if(ev->button() == Qt::LeftButton){
QString str = QString("鼠标释放: x= %1 , y= %2").arg(ev->x()).arg(ev->y());
qDebug()<<str;
}
}
//鼠标移动
void MyLabel::mouseMoveEvent(QMouseEvent *ev){
//按位与运算&
if(ev->buttons() & Qt::LeftButton){
QString str = QString("鼠标移动: x= %1 , y= %2").arg(ev->x()).arg(ev->y());
qDebug()<<str;
}
}