QGraphicsView(缩放,平移,旋转)

本文介绍了如何创建一个自定义的MyGraphicsView类,它扩展了QGraphicsView,包含事件过滤器来处理滚轮缩放和平移以及鼠标右键点击的旋转操作。
摘要由CSDN通过智能技术生成

东西不多直接上代码,一共一个类两函数,两函数还有一个是构造。

//头文件
#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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值