通过label来显示各种事件
鼠标按下事件
//按下显示坐标
void MyLabel::mousePressEvent(QMouseEvent * ev)
{int i = ev->x();int j = ev->y();//判断按下的鼠标键位if (ev->button() == Qt::LeftButton) {qDebug() << "LeftButton";}else if (ev->button() == Qt::RightButton) {qDebug() << "RightButton";}else if (ev->button() == Qt::MidButton){qDebug() << "MidButton";}QString text = QString("<center><h1>Mouse Press:(%1,%2)</center></h1>").arg(i).arg(j);this->setText(text);
}
鼠标抬起事件
//鼠标抬起
void MyLabel::mouseReleaseEvent(QMouseEvent* ev)
{QString text = QString("<center><h1>Mouse Release:(%1,%2)</center></h1>").arg(ev->x()).arg(ev->y());this->setText(text);
}
鼠标移动事件
//鼠标移动,不设置this->setMouseTracking(true);需要按下后移动才有效
void MyLabel::mouseMoveEvent(QMouseEvent* ev)
{QString text = QString("<center><h1>Mouse Move:(%1,%2)</center></h1>").arg(ev->x()).arg(ev->y());this->setText(text);
}
#include "MyLabel.h"
#include <QMouseEvent>
#include <QDebug>MyLabel::MyLabel(QWidget *parent): QLabel(parent)
{//设置默认追踪鼠标,就可以不先点击就触发移动事件this->setMouseTracking(true);
}MyLabel::~MyLabel()
{}//按下显示坐标
void MyLabel::mousePressEvent(QMouseEvent * ev)
{int i = ev->x();int j = ev->y();//判断按下的鼠标键位if (ev->button() == Qt::LeftButton) {qDebug() << "LeftButton";}else if (ev->button() == Qt::RightButton) {qDebug() << "RightButton";}else if (ev->button() == Qt::MidButton){qDebug() << "MidButton";}QString text = QString("<center><h1>Mouse Press:(%1,%2)</center></h1>").arg(i).arg(j);this->setText(text);
}//鼠标抬起
void MyLabel::mouseReleaseEvent(QMouseEvent* ev)
{QString text = QString("<center><h1>Mouse Release:(%1,%2)</center></h1>").arg(ev->x()).arg(ev->y());this->setText(text);
}//鼠标移动,不设置this->setMouseTracking(true);需要按下后移动才有效
void MyLabel::mouseMoveEvent(QMouseEvent* ev)
{QString text = QString("<center><h1>Mouse Move:(%1,%2)</center></h1>").arg(ev->x()).arg(ev->y());this->setText(text);
}