Qt鼠标滚轮事件代码

interactiveview.h

#ifndefINTERACTIVE_VIEW_H

#defineINTERACTIVE_VIEW_H

 

#include<QGraphicsView>

 

classQWheelEvent;

classQKeyEvent;

 

classInteractiveView:publicQGraphicsView

{

    Q_OBJECT

public:

     InteractiveView(QWidget*parent=0);

 

    //平移速度

    voidsetTranslateSpeed(qrealspeed);

    qrealtranslateSpeed()const;

 

    //缩放的增量

    voidsetZoomDelta(qrealdelta);

    qrealzoomDelta()const;

 

protected:

    //上/下/左/右键向各个方向移动、加/减键进行缩放、空格/回车键旋转

    voidkeyPressEvent(QKeyEvent*event)Q_DECL_OVERRIDE;

    //平移

    voidmouseMoveEvent(QMouseEvent*event)Q_DECL_OVERRIDE;

    voidmousePressEvent(QMouseEvent*event)Q_DECL_OVERRIDE;

    voidmouseReleaseEvent(QMouseEvent*event)Q_DECL_OVERRIDE;

    //放大/缩小

    voidwheelEvent(QWheelEvent*event)Q_DECL_OVERRIDE;

    voidmouseDoubleClickEvent(QMouseEvent*event)Q_DECL_OVERRIDE;

 

publicQ_SLOTS:

    voidzoomIn();  //放大

    voidzoomOut();  //缩小

    voidzoom(floatscaleFactor);//缩放-scaleFactor:缩放的比例因子

    voidtranslateF(QPointFdelta);  //平移

 

private:

    Qt::MouseButtonm_translateButton;  //平移按钮

    qrealm_translateSpeed;  //平移速度

    qrealm_zoomDelta;  //缩放的增量

    boolm_bMouseTranslate;  //平移标识

    QPointm_lastMousePos;  //鼠标最后按下的位置

    qrealm_scale;  //缩放值

};

 

#endif//INTERACTIVE_VIEW_H

interactiveview.cpp

#include"interactiveview.h"
#include<QWheelEvent>
#include<QKeyEvent>
#include<QScrollBar>
#include<QDebug>
 
#defineVIEW_CENTERviewport()->rect().center()
#defineVIEW_WIDTH  viewport()->rect().width()
#defineVIEW_HEIGHTviewport()->rect().height()
 
InteractiveView::InteractiveView(QWidget*parent)
    :QGraphicsView(parent),
      m_translateButton(Qt::LeftButton),
      m_scale(1.0),
      m_zoomDelta(0.1),
      m_translateSpeed(1.0),
      m_bMouseTranslate(false)
{
 
    //去掉滚动条
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
 
    setCursor(Qt::PointingHandCursor);
    setRenderHint(QPainter::Antialiasing);
 
    setSceneRect(INT_MIN/2,INT_MIN/2,INT_MAX,INT_MAX);
    centerOn(0,0);
 
}
 
//平移速度
voidInteractiveView::setTranslateSpeed(qrealspeed)
{
    //建议速度范围
    Q_ASSERT_X(speed>=0.0&&speed<=2.0,
               "InteractiveView::setTranslateSpeed","Speedshouldbeinrange[0.0,2.0].");
    m_translateSpeed=speed;
}
 
qrealInteractiveView::translateSpeed()const
{
    returnm_translateSpeed;
}
 
//缩放的增量
voidInteractiveView::setZoomDelta(qrealdelta)
{
    //建议增量范围
    Q_ASSERT_X(delta>=0.0&&delta<=1.0,
               "InteractiveView::setZoomDelta","Deltashouldbeinrange[0.0,1.0].");
    m_zoomDelta=delta;
}
 
qrealInteractiveView::zoomDelta()const
{
    returnm_zoomDelta;
}
 
//上/下/左/右键向各个方向移动、加/减键进行缩放、空格/回车键旋转
voidInteractiveView::keyPressEvent(QKeyEvent*event)
{
    switch(event->key()){
    caseQt::Key_Up:
        translateF(QPointF(0,-2));  //上移
        break;
    caseQt::Key_Down:
        translateF(QPointF(0,2));  //下移
        break;
    caseQt::Key_Left:
        translateF(QPointF(-2,0));  //左移
        break;
    caseQt::Key_Right:
        translateF(QPointF(2,0));  //右移
        break;
    caseQt::Key_Plus:  //放大
        zoomIn();
        break;
    caseQt::Key_Minus:  //缩小
        zoomOut();
        break;
    caseQt::Key_Space:  //逆时针旋转
        rotate(-5);
        break;
    caseQt::Key_Enter:  //顺时针旋转
    caseQt::Key_Return:
        rotate(5);
        break;
    default:
        QGraphicsView::keyPressEvent(event);
    }
}
 
//平移
voidInteractiveView::mouseMoveEvent(QMouseEvent*event)
{
    if(m_bMouseTranslate){
        setCursor(Qt::ClosedHandCursor);
        QPointFmouseDelta=mapToScene(event->pos())-mapToScene(m_lastMousePos);
        translateF(mouseDelta);
        qDebug()<<"mouseMove";
    }
    m_lastMousePos=event->pos();
    QGraphicsView::mouseMoveEvent(event);
}
 
voidInteractiveView::mousePressEvent(QMouseEvent*event)
{
    if(event->button()==m_translateButton){
        //  QPointFpoint=mapToScene(event->pos());
        //  if(scene()->itemAt(point,transform())==NULL)  {  //当光标底下没有item时,才能移动
        m_bMouseTranslate=true;
        m_lastMousePos=event->pos();
        setCursor(Qt::ArrowCursor);
         qDebug()<<"mousePress";
        //   }
    }
    QGraphicsView::mousePressEvent(event);
}
 
voidInteractiveView::mouseReleaseEvent(QMouseEvent*event)
{
    if(event->button()==m_translateButton){
        m_bMouseTranslate=false;
        setCursor(Qt::ArrowCursor);
        qDebug()<<"mouseRelease";
    }
    QGraphicsView::mouseReleaseEvent(event);
}
 
//放大/缩小
voidInteractiveView::wheelEvent(QWheelEvent*event)
{
    setCursor(Qt::BusyCursor);
    QPointscrollAmount=event->angleDelta();
    scrollAmount.y()>0?zoomIn():zoomOut();
    setCursor(Qt::ArrowCursor);
    qDebug()<<"mouseWheel";
}
 
voidInteractiveView::mouseDoubleClickEvent(QMouseEvent*event)
{
  //  centerOn(0,0);
}
 
//放大
voidInteractiveView::zoomIn()
{
    zoom(1+m_zoomDelta);
}
 
//缩小
voidInteractiveView::zoomOut()
{
    zoom(1-m_zoomDelta);
}
 
//缩放-scaleFactor:缩放的比例因子
voidInteractiveView::zoom(floatscaleFactor)
{
    m_scale*=scaleFactor;
    //防止过小或过大
//    qrealfactor=transform().scale(scaleFactor,scaleFactor).mapRect(QRectF(0,0,1,1)).width();
//    if(factor<0.07||factor>100)
//        return;
    QPointFoldPos=mapToScene(m_lastMousePos);
    scale(scaleFactor,scaleFactor);
    QPointFnewPos=mapToScene(m_lastMousePos);
    translateF(newPos-oldPos);
 
}
 
//平移
voidInteractiveView::translateF(QPointFdelta)
{
    //根据当前zoom缩放平移数
    delta*=m_scale;
    delta*=m_translateSpeed;
 
    //  view根据鼠标下的点作为锚点来定位scene
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    QPointnewCenter(VIEW_WIDTH/2-delta.x(),  VIEW_HEIGHT/2-delta.y());
    centerOn(mapToScene(newCenter));
 
    //sceneview的中心点作为锚点
    setTransformationAnchor(QGraphicsView::AnchorViewCenter);
}
 

mainwindow.cpp

#include"mainwindow.h"
#include"ui_mainwindow.h"
#include<QGraphicsRectItem>
#include<QGraphicsPixmapItem>
#include<QFileDialog>
 
MainWindow::MainWindow(QWidget*parent):
    QMainWindow(parent),
    ui(newUi::MainWindow)
{
    ui->setupUi(this);
    QGraphicsScene*scene=newQGraphicsScene;
    scene->addPixmap(QPixmap("e:/2.jpg"));
    ui->graphicsView->setScene(scene);
 
}
 
MainWindow::~MainWindow()
{
    deleteui;
}
 
voidMainWindow::on_pushButton_clicked()
{
    QImage*image;
    image=newQImage();
    QStringfileName=QFileDialog::getOpenFileName(
                this,"openimagefile",
                ".",
                "Imagefiles(*.bmp*.jpg*.pbm*.pgm*.png*.ppm*.xbm*.xpm);;Allfiles(*.*)");
    if(fileName!="")
    {
        if(image->load(fileName))
        {
            QGraphicsScene*scene=newQGraphicsScene;
            scene->addPixmap(QPixmap::fromImage(*image));
            ui->graphicsView->setScene(scene);
           }
    }
}

mymouseevent.h

#ifndefMYMOUSEEVENT_H
#defineMYMOUSEEVENT_H
 
#include<QWidget>
 
namespaceUi{
classmyMouseEvent;
}
 
classmyMouseEvent:publicQWidget
{
    Q_OBJECT
 
public:
    explicitmyMouseEvent(QWidget*parent=0);
    ~myMouseEvent();
    QPointoffset;
 
private:
    Ui::myMouseEvent*ui;
protected:
    voidmousePressEvent(QMouseEvent*event);
    voidwheelEvent(QWheelEvent*event);
    voidmouseMoveEvent(QMouseEvent*event);
    voidmouseDoubleClickEvent(QMouseEvent*event);//感觉没有体现鼠标被点击了2
    voidmouseReleaseEvent(QMouseEvent*event);
};
 
#endif//MYMOUSEEVENT_H

mymouseevent.cpp

#include"mymouseevent.h"
#include"ui_mymouseevent.h"
#include<QMouseEvent>
#include<QDebug>
//myMouseEvent::myMouseEvent(QWidget*parent):
//    QWidget(parent),
//    ui(newUi::myMouseEvent)
//{
//    ui->setupUi(this);
//}
 
myMouseEvent::~myMouseEvent()
{
    deleteui;
}
myMouseEvent::myMouseEvent(QWidget*parent)
    :QWidget(parent),ui(newUi::myMouseEvent)
{
 
    {
        ui->setupUi(this);
    }
 
    //setcursor
    QCursorcursor;
    cursor.setShape(Qt::OpenHandCursor);
    setCursor(cursor);
}
 
//重写父类中虚函数,可以直接运行,不需要再次建立信号传递(与wxWidgets区分)
voidmyMouseEvent::mousePressEvent(QMouseEvent*event)
{
    if(event->button()==Qt::LeftButton){
        QCursorcursor;
        cursor.setShape(Qt::ClosedHandCursor);
        QApplication::setOverrideCursor(cursor);
        //globalPos()是鼠标指针相对于屏幕左上角的坐标,pos()是窗体左上角相对于屏幕左上角的坐标(获取未移动前的窗体位置)
        offset=event->globalPos()-pos();
    }
    elseif(event->button()==Qt::RightButton){
        QCursorcursor(QPixmap("../image/itk.png"));//2个点表示上级目录
        QApplication::setOverrideCursor(cursor);
    }
 
}
 
voidmyMouseEvent::mouseReleaseEvent(QMouseEvent*event)
{
    QApplication::restoreOverrideCursor();
}
 
voidmyMouseEvent::mouseDoubleClickEvent(QMouseEvent*event)//感觉没有体现鼠标被点击了2
{
    if(event->button()==Qt::LeftButton){
        if(windowState()!=Qt::WindowFullScreen)
            setWindowState(Qt::WindowFullScreen);
        elsesetWindowState(Qt::WindowNoState);
    }
}
 
voidmyMouseEvent::mouseMoveEvent(QMouseEvent*event)
{
    if(event->buttons()&Qt::LeftButton){//与运算
        QPointtemp;
        temp=event->globalPos()-offset;//
        move(temp);//移动到具体坐标点
        qDebug()<<"globalPos"<<event->globalPos()<<endl;
        qDebug()<<"pos"<<pos()<<endl;
    }
}
 
voidmyMouseEvent::wheelEvent(QWheelEvent*event)
{
    if(event->delta()>0){
        ui->textEdit->zoomIn();//放大
    }else{
        ui->textEdit->zoomOut();//缩小
    }
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页