Qt 滑鼠事件和滾輪事件
阿新 • • 發佈:2020-12-11
文章目錄
.pro檔案
#------------------------------------------------- # # Project created by QtCreator 2016-05-30T21:45:56 # #------------------------------------------------- QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = mymouseevent TEMPLATE = app SOURCES += main.cpp\ widget.cpp HEADERS += widget.h FORMS += widget.ui
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QMouseEvent>
Widget:: Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QCursor cursor; // 建立游標物件
cursor.setShape(Qt::OpenHandCursor); // 設定游標形狀
setCursor(cursor); // 使用游標
}
Widget::~Widget()
{
delete ui;
}
void Widget::mousePressEvent (QMouseEvent *event) // 滑鼠按下事件
{
if(event->button() == Qt::LeftButton){ // 如果是滑鼠左鍵按下
QCursor cursor;
cursor.setShape(Qt::ClosedHandCursor);
QApplication::setOverrideCursor(cursor); // 使滑鼠指標暫時改變形狀
offset = event->globalPos() - pos(); // 獲取指標位置和視窗位置的差值
}
else if(event->button() == Qt::RightButton){ // 如果是滑鼠右鍵按下
QCursor cursor(QPixmap("../mymouseevent/logo.png"));
QApplication::setOverrideCursor(cursor);// 使用自定義的圖片作為滑鼠指標
}
}
void Widget::mouseMoveEvent(QMouseEvent *event) // 滑鼠移動事件
{
if(event->buttons() & Qt::LeftButton){ // 這裡必須使用buttons()
QPoint temp;
temp = event->globalPos() - offset;
move(temp);// 使用滑鼠指標當前的位置減去差值,就得到了視窗應該移動的位置
}
}
void Widget::mouseReleaseEvent(QMouseEvent *event) // 滑鼠釋放事件
{
Q_UNUSED(event);
QApplication::restoreOverrideCursor(); // 恢復滑鼠指標形狀
}
void Widget::mouseDoubleClickEvent(QMouseEvent *event) // 滑鼠雙擊事件
{
if(event->button() == Qt::LeftButton){ // 如果是滑鼠左鍵按下
if(windowState() != Qt::WindowFullScreen) // 如果現在不是全屏
setWindowState(Qt::WindowFullScreen); // 將視窗設定為全屏
else setWindowState(Qt::WindowNoState); // 否則恢復以前的大小
}
}
void Widget::wheelEvent(QWheelEvent *event) // 滾輪事件
{
if(event->delta() > 0){ // 當滾輪遠離使用者時
ui->textEdit->zoomIn(); // 進行放大
}else{ // 當滾輪向使用者方向旋轉時
ui->textEdit->zoomOut(); // 進行縮小
}
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
QPoint offset; // 用來儲存滑鼠指標位置與視窗位置的差值
protected:
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseDoubleClickEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void wheelEvent(QWheelEvent *event);
};
#endif // WIDGET_H