《Qt5+鼠标事件》

版权声明:本文为博主原创文章,未经博主允许不得转载,博客地址:http://blog.csdn.net/mars_xiaolei。 https://blog.csdn.net/mars_xiaolei/article/details/83543930

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
protected:
    void mousePressEvent(QMouseEvent *e);
    void mouseMoveEvent(QMouseEvent *e);
    void mouseReleaseEvent(QMouseEvent *e);
    void mouseDoubleClickEvent(QMouseEvent *e);

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMouseEvent>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle(tr("鼠标事件"));//设置窗体标题
    ui->statusLabel->setText(tr("当前位置:"));//显示鼠标实时移动的位置
    ui->statusLabel->setFixedWidth(100);
    ui->mousePosLabel->setText(tr(""));//显示鼠标按下或者释放的位置
    ui->mousePosLabel->setFixedWidth(100);
    statusBar()->addPermanentWidget(ui->statusLabel);//在状态栏中添加statusLabel控件
    statusBar()->addPermanentWidget(ui->mousePosLabel);//在状态栏中添加mousePosLabel控件
    this->setMouseTracking(true);//设置窗体追踪鼠标
    resize(400,200);
}

void MainWindow::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 MainWindow::mouseMoveEvent(QMouseEvent *e)
{
   ui->mousePosLabel->setText("("+QString::number(e->x())+", "+QString::number(e->y())+")");
}

void MainWindow::mouseReleaseEvent(QMouseEvent *e)
{
    QString str="("+QString::number(e->x())+","+QString::number(e->y())+")";
    statusBar()->showMessage(tr("释放在:")+str,3000);
}

void MainWindow::mouseDoubleClickEvent(QMouseEvent *e){;}

MainWindow::~MainWindow()
{
    delete ui;
}

完整源码链接:https://pan.baidu.com/s/1t3FqHWe9Y3USw7_Ru59BeQ 

提取码:f0tk

猜你喜欢

转载自blog.csdn.net/mars_xiaolei/article/details/83543930