// MyLabel.h
#ifndef MYLABEL_H
#define MYLABEL_H
#include <QLabel>
class MyLabel : public QLabel
{
Q_OBJECT
public:
explicit MyLabel(QWidget *parent = nullptr);
void enterEvent(QEvent *event);
void leaveEvent(QEvent *event);
virtual void mouseMoveEvent(QMouseEvent *ev);
virtual void mousePressEvent(QMouseEvent *ev);
virtual void mouseReleaseEvent(QMouseEvent *ev);
signals:
public slots:
};
#endif // MYLABEL_H
// MyLabel.cpp
#include "MyLabel.h"
#include <QDebug>
#include <QMouseEvent>
MyLabel::MyLabel(QWidget *parent) : QLabel(parent)
{
// mouseMoveEvent 函数变成 触摸即触发
this->setMouseTracking(true);
}
void MyLabel::enterEvent(QEvent *event) {
qDebug() << __func__ << event;
}
void MyLabel::leaveEvent(QEvent *event) {
qDebug() << __func__ << event;
}
void MyLabel::mouseMoveEvent(QMouseEvent *ev) {
// globalX, globalY: (屏幕x, 屏幕y)
QString str = QString("mouseMoveEvent: x = %1, y = %2, globalX = %3, globalY = %4").arg(ev->x()).arg(ev->y()).arg(ev->globalX()).arg(ev->globalY());
qDebug() << __func__ << str;
}
void MyLabel::mousePressEvent(QMouseEvent *ev) {
if (ev->button() == Qt::LeftButton) { // 判断左键
qDebug() << __func__ << ev;
}
}
void MyLabel::mouseReleaseEvent(QMouseEvent *ev) {
if (ev->button() == Qt::LeftButton) { // 判断左键
qDebug() << __func__ << ev;
}
}