Search code examples
c++qtqgraphicsviewqgraphicsscene

QT Graphic scene/view - moving around with mouse


I created my own classes (view and scene) to display image and objects I added to it, even got zoom in/out function implemented to my view, but now I have to add new functionality and I don't even know how to start looking for it.

  • Whenever I press the scroll button of my mouse and hold it - I wish to move around the scene, to see different parts of it - just like I would with sliders. It is supposed to be similar to any other program allowing to zoom in/out to image and move around zoomed picture to see different parts of it.

Unfortunately - I don't even know how to look for some basic, because "moving" and similar refer to dragging objects around.

EDIT 1

void CustomGraphicView::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::MidButton)
    {
        setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        translate(event->x(),event->y());
    }
}

Tried this - but it is working in reverse.


Solution

  • I suppose you know how to handle events using Qt.

    So, to translate (move) your view use the QGraphicsView::translate() method.

    EDIT

    How to use it:

    void CustomGraphicsView::mousePressEvent(QMouseEvent* event)
    {
        if (e->button() == Qt::MiddleButton)
        {
            // Store original position.
            m_originX = event->x();
            m_originY = event->y();
        }
    }
    
    void CustomGraphicsView::mouseMoveEvent(QMouseEvent* event)
    {
        if (e->buttons() & Qt::MidButton)
        {
            QPointF oldp = mapToScene(m_originX, m_originY);
            QPointF newP = mapToScene(event->pos());
            QPointF translation = newp - oldp;
    
            translate(translation.x(), translation.y());
    
            m_originX = event->x();
            m_originY = event->y();
        }
    }