I am currently able to load my image into a grahpics scene, and then again into a QGraphicsViewer.
I am able to implement a zoom feature by dtecting a QEvent::Wheel and then calling the graphicsViews's scale() function.
However, I can't seem to figure out how to get the pan functionality working. I basically want to detect when a mouse has clicked down on the image, and then move the image left, right, up or down along with the mouse.
As of right now, I basically have a MouseFilter class that is detecting events, and doing different things depending on the event type. I attached that listener to the QGraphicsView object
In case someone is wondering how to do it on their own, it's actually quite simple. Here's the code from my app:
class ImageView : public QGraphicsView { public: ImageView(QWidget *parent); ~ImageView(); private: virtual void mouseMoveEvent(QMouseEvent *event); virtual void mousePressEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); bool _pan; int _panStartX, _panStartY; };
You need to store the start position of the drag, for example like this (I used the right button):
void ImageView::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { _pan = true; _panStartX = event->x(); _panStartY = event->y(); setCursor(Qt::ClosedHandCursor); event->accept(); return; } event->ignore(); }
Also, you need to clear the flag and restore the cursor once the button is released:
void ImageView::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { _pan = false; setCursor(Qt::ArrowCursor); event->accept(); return; } event->ignore(); }
To actually manage the drag, you need to override the mouse move event. QGraphicsView inherits a QAbstractScrollArea, and its scrollbars are easily accessible. You also need to update the pan position:
void ImageView::mouseMoveEvent(QMouseEvent *event) { if (_pan) { horizontalScrollBar()->setValue(horizontalScrollBar()->value() - (event->x() - _panStartX)); verticalScrollBar()->setValue(verticalScrollBar()->value() - (event->y() - _panStartY)); _panStartX = event->x(); _panStartY = event->y(); event->accept(); return; } event->ignore(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With