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);
</