QT鼠标事件和滚轮事件学习


鼠标事件和滚轮事件
QMouseEvent类用来表示一个鼠标事件,在窗口部件中按下鼠标或者移动鼠标指针时,都会产生鼠标事件。通过QMouseEvent类可以获取鼠标是哪个键被按下、鼠标指针(光标)的当前位置。
QWheelEvent类用来表示鼠标滚轮事件,主要用来获取滚轮移动的方向和距离。

代码

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
protected:
    void mousePressEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent *event);
    void mouseDoubleClickEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    void wheelEvent(QWheelEvent *event);
private:
    Ui::Widget *ui;
    QPoint offset; // 用来存储鼠标指针位置与窗口位置的差值
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QMouseEvent>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    QCursor cursor; // 创建光标对象
    cursor.setShape(Qt::OpenHandCursor); // 设置光标形状 鼠标进入窗口改为小手掌形状 Qt助手中搜索Qt::CursorShape关键字查看常用的鼠标形状
    setCursor(cursor); // 使用光标
    // setMouseTracking(true); // 设置鼠标跟踪 不按键也能获取鼠标移动事件
    ui->setupUi(this);
}

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

void Widget::mousePressEvent(QMouseEvent *event) // 鼠标按下事件
{
    if (event->type() == Qt::LeftButton) { // 鼠标左键按下
        QCursor cursor;
        cursor.setShape(Qt::ClosedHandCursor); //设置光标形状为抓起来的小手
        offset =event->globalPos() - pos(); // 获取指针位置和窗口位置的差值
    } else if (event->type() == Qt::RightButton) { // 鼠标右键按下
        QCursor cursor(QPixmap(":/logo.png"));
        QApplication::setOverrideCursor(cursor); // 使用自定义的图片作为鼠标指针
    }
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) { // button函数无法获取哪个键被按下,buttons可以,buttons按位与Qt::LeftButton判断鼠标左键是否按下
        QPoint temp;
        temp = event->globalPos() - offset;
        move(temp); // 使用鼠标指针当前的位置减去差值,就得到了窗口应该移动的位置
    }
}

void Widget::mouseReleaseEvent(QMouseEvent *event) // 释放鼠标事件
{
    Q_UNUSED(event);
    QApplication::restoreOverrideCursor(); // 恢复鼠标指针形状 restoreOverrideCursor要和setOverrideCursor函数配合使用
}

void Widget::mouseDoubleClickEvent(QMouseEvent *event) // 鼠标双击事件
{
    if (event->button() == Qt::LeftButton) { // 鼠标左键按下
        if (windowState() != Qt::WindowFullScreen) { // 当前不是全屏
            setWindowState(Qt::WindowFullScreen); // 将窗口设置成全屏 setWindowState设置窗口全屏或者恢复原来大小
        } else {
            setWindowState(Qt::WindowNoState); // 恢复原来的大小
        }
    }
}

void Widget::wheelEvent(QWheelEvent *event) // 滚轮事件 在设计界面拖入一个 Text Edit
{
    if (event->delta() > 0) { // 滚轮远离使用者
        ui->textEdit->zoomIn(); // 进行放大
    } else {
        ui->textEdit->zoomOut(); // 进行缩小
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM