作者:月在杏花枝 | 来源:互联网 | 2023-10-12 11:07
QT是事件驱动的,监听事件自然也是一个重点啦。首先是监听鼠标事件。新建项目,基于mainwindow头文件:#ifndefMOUSEEVENT_H#defineMOUSEEVENT_H#inclu
QT是事件驱动的,监听事件自然也是一个重点啦。首先是监听鼠标事件。
新建项目,基于mainwindow头文件:
#ifndef MOUSEEVENT_H
#define MOUSEEVENT_H
#include
#include
#include
#include
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 *);
private:
QLabel *statusLabel;
QLabel *mousePosLabel;
};
#endif // MOUSEEVENT_H
主要代码:
#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);
}
MouseEvent::~MouseEvent()
{
}
void MouseEvent::mousePressEvent(QMouseEvent *e)
{
QString str="("+QString::number(e->x())+","+QString::number
(e->y())+")";
if(e->button()==Qt::LeftButton)
{
statusBar()->showMessage(tr("左键")+str);
}
if(e->button()==Qt::RightButton)
{
statusBar()->showMessage(tr("右键")+str);
}
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 *)
{
}
这里的
setMouseTracking()函数,是用来决定是否 实时追踪鼠标,默认的是false。可是我们需要实时获得鼠标的位置,因此需要设置诶true。
运行效果: