1. 程式人生 > 其它 >QT滑鼠事件和滾輪事件學習

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(); // 進行縮小 } }