东西不多直接上代码,一共一个类两函数,两函数还有一个是构造。
//头文件
#pragma once
#include <QGraphicsView>
#include<QEvent>
#include<QGraphicsScene>
class MyGraphicsView : public QGraphicsView
{
Q_OBJECT
public:
explicit MyGraphicsView(QWidget *parent = 0);
~MyGraphicsView();
bool eventFilter(QObject *watched, QEvent *event);
QGraphicsScene *mScene;
private:
public slots:
};
#include "MyGraphicsView.h"
#include<QMouseEvent>
#include<QApplication>
#include<QGraphicsPixmapItem>
MyGraphicsView::MyGraphicsView(QWidget *parent) :
QGraphicsView(parent)
{
QString PixPath =qApp->applicationDirPath()+"/222.png"; //资源文件路径
viewport()->installEventFilter(this);
mScene = new QGraphicsScene;
setScene(mScene);
mScene->installEventFilter(this);
setDragMode(QGraphicsView::ScrollHandDrag); //开启平移
mScene->addPixmap(QPixmap(PixPath))->setPos(50,100);
mScene->addPixmap(QPixmap(PixPath))->setPos(200,100);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
MyGraphicsView::~MyGraphicsView()
{
}
bool MyGraphicsView::eventFilter(QObject *watched, QEvent *event)
{
if (watched == viewport())
{
if (event->type()==QEvent::Wheel)//滚轮放大
{
QWheelEvent * WheelEvent = (QWheelEvent*)event;
int detal =WheelEvent->delta();
detal>0?scale(1.1,1.1):scale(1/1.1,1/1.1);
return true;
}
if (event->type()==QEvent::MouseButtonPress)//鼠标点击旋转
{
QMouseEvent * MouseEven = (QMouseEvent*)event;
MouseEven->buttons() == Qt::RightButton?rotate(45):void();
return false;
}
return false;
}
else
return QGraphicsView::eventFilter(watched,event);
}
效果图
uiview 2024-04-10 02-43-01