C++版QT:鼠标事件

鼠标常用的事件可以说有一下几种:鼠标按下、鼠标移动、鼠标移动、鼠标双击和鼠标滚轮事件。

当你想使用他们,需要包含头文件:#include

需要对鼠标事件进行处理时,通常要重新实现以下几个鼠标事件处理函数:

QWidget::mousePressEvent()
QWidget::mouseReleaseEvent()
QWidget::mouseDoubleClickEvent()
QWidget::mouseMoveEvent()

鼠标左键:Qt::LeftButton

鼠标中键:Qt::MidButton

鼠标右键:Qt::RightButton

下面是一个实例:

mouseevent.h

#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 *e);
private:
    QLabel *statusLabel;
    QLabel *MousePosLabel;
};
​
#endif // MOUSEEVENT_H
​

mouseevent.cpp

#include "mouseevent.h"
#pragma execution_character_set("utf-8")
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);
    }
    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){}
​

main.cpp

#include "mouseevent.h"
#include 
​
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MouseEvent w;
    w.show();
    
    return a.exec();
}
​

C++版QT:鼠标事件_第1张图片

你可能感兴趣的:(C++学习与记录,c++,QT,鼠标事件)