鼠標事件和滾輪事件
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(); // 進行縮小 } }
