C++ (Qt)class State{public: virtual void mouseMove(...) = 0; virtual void mousePress(...) = 0; virtual void keyboarPress(...) = 0;}; // Переопределить методы для режима zoomclass ZoomState : public State{public: virtual void mouseMove(...); virtual void mousePress(...); virtual void keyboarPress(...);}; // Переопределить методы для режима rotateclass RotateState : public State{public: virtual void mouseMove(...); virtual void mousePress(...); virtual void keyboarPress(...);};
C++ (Qt)// currentState это указатель на State void classGraphicsScene::mouseMoveEvent(...){ currentState->mouseMove(...);} void classGraphicsScene::mousePressEvent(...){ currentState->mousePress(...);}
C++ (Qt)#ifndef RVIEWWATCHER_H#define RVIEWWATCHER_H #include <QObject> class QGraphicsView;class QEvent; class RViewWatcher : public QObject{ Q_OBJECTpublic: RViewWatcher(QGraphicsView *view, QObject *parent); int state() const;public slots: void setState(int id);protected: typedef bool (*Delegate)(QGraphicsView *, QEvent *); Delegate _handler; int _state; bool eventFilter(QObject *watched, QEvent *event);}; #endif // RVIEWWATCHER_H
C++ (Qt)#include "rviewwatcher.h"#include <QGraphicsView>#include <QEvent>#include <QMouseEvent> bool zoomer(QGraphicsView *view, QEvent *event){ static const qreal ZOOM_FACTOR = 1.05; if (event->type() != QEvent::MouseButtonPress) return false; QMouseEvent *e = static_cast<QMouseEvent *>(event); switch (e->button()) { case Qt::LeftButton: view->setMatrix(QMatrix(ZOOM_FACTOR, 0, 0, ZOOM_FACTOR, 0, 0), true); break; case Qt::RightButton: view->setMatrix(QMatrix(1/ZOOM_FACTOR, 0, 0, 1/ZOOM_FACTOR, 0, 0), true); break; case Qt::MidButton: view->resetMatrix(); break; default: return false; } return true;} bool doNothing(QGraphicsView *view, QEvent *event){ return false;} RViewWatcher::RViewWatcher(QGraphicsView *view, QObject *parent) : QObject(parent){ view->installEventFilter(this); setState(1);} int RViewWatcher::state() const{ return _state;} void RViewWatcher::setState(int id){ switch (id) { case 0: _handler = zoomer; break; case 1: _handler = doNothing; break; default: Q_ASSERT(false); }} bool RViewWatcher::eventFilter(QObject *watched, QEvent *event){ if (!qobject_cast<QGraphicsView *>(watched)) return false; return _handler(static_cast<QGraphicsView *>(watched), event);}