Qt-事件处理-鼠标事件

时间:2022-08-14 18:55:40

根据书中的内容,简单的实现鼠标相关的内容

源代码如下

.h
#ifndef MOUSEEVENT_H
#define MOUSEEVENT_H #include <QMainWindow>
#include <QLabel>
#include <QStatusBar>
#include <QMouseEvent>
class MouseEvent : public QMainWindow
{
Q_OBJECT public:
MouseEvent(QWidget *parent = 0);
~MouseEvent();
protected:
void mousePressEvent(QMouseEvent *e);
void mouseMoveEvent(QMouseEvent *e);
void mouseReleaseEvent(QMouseEvent *e);
void mouseDoubleClickEvent(QMouseEvent *e);
private:
QLabel *statusLabel;
QLabel *MousePosLabel;
}; #endif // MOUSEEVENT_H
.cpp
#include "mouseevent.h" MouseEvent::MouseEvent(QWidget *parent)
: QMainWindow(parent)
{
setWindowTitle(tr("鼠标事件"));
statusLabel = new QLabel;
statusLabel->setText(tr("当前位置"));
statusLabel->setFixedWidth(100);
MousePosLabel = new QLabel;
MousePosLabel->setText(tr(""));
MousePosLabel->setFixedWidth(100);
statusBar()->addPermanentWidget(statusLabel);
statusBar()->addPermanentWidget(MousePosLabel);
this->setMouseTracking(true);
resize(400,200);
} void MouseEvent::mousePressEvent(QMouseEvent *e)
{
QString str="("+QString::number(e->x())+","+QString::number(e->y()) +")";
if(e->button()==Qt::LeftButton)
{
statusBar()->showMessage(tr("左键")+str);
}
else if(e->button()==Qt::RightButton)
{
statusBar()->showMessage(tr("右键")+str);
}
else if(e->button()==Qt::MidButton)
{
statusBar()->showMessage(tr("中键")+str);
}
} void MouseEvent::mouseMoveEvent(QMouseEvent *e)
{
MousePosLabel->setText("("+QString::number(e->x())+","+QString::number(e->y())+")");
} void MouseEvent::mouseReleaseEvent(QMouseEvent *e)
{
QString str="("+QString::number(e->x())+","+QString::number(e->y()) +")";
statusBar()->showMessage(tr("释放在:")+str,3000);
} void MouseEvent::mouseDoubleClickEvent(QMouseEvent *e){} MouseEvent::~MouseEvent()
{ }

工程代码:https://gitee.com/DreamLife-Technology_DreamLife/MouseEvent

Qt-事件处理-鼠标事件