Qt 鼠标事件和滚轮事件

QMouseEvent类表示一个鼠标事件,窗口中的按下,移动都会产生鼠标事件。

QWheelEvent用来表示滚轮事件,获取滚轮的移动方向和距离。

本案例效果:在文本框与框外鼠标样式改变,双击全屏,右击样式改变滑轮缩放文本框内内容。


.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();

private:
    Ui::Widget *ui;

    QPoint offset;
protected:
    void mouseMoveEvent(QMouseEvent *event) ;
    void mouseReleaseEvent(QMouseEvent *event) ;
    void mouseDoubleClickEvent(QMouseEvent *event) ;
    void mousePressEvent(QMouseEvent *event);
    void wheelEvent(QWheelEvent *event );
};
#endif // WIDGET_H

.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/dddd.png"));
        QApplication::setOverrideCursor(cursor);
    }
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton){ //注意!!!!必须为buttons,不是button,否则拖拽无效
        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(); //缩小
    }
}

 


版权声明:本文为baidu_33879812原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。