How to move QGraphicsScene by dragging with mouse?



  • Hey,
    I already found this thread: https://stackoverflow.com/questions/35865161/qt-graphic-scene-view-moving-around-with-mouse
    But this doesn't work in my program, the scene just goes back every time I move the mouse (pressed) to the point where I first clicked on the scene... (I don't really understynd that too). Maybe it has something to do with the fact, that my scene is larger than its viewport.
    Any ideas how I could make this?
    Thanks for answers


  • Lifetime Qt Champion

    Hi,

    Showing your implementation will likely helps us help you finding what's going wrong.

    You should also which version of Qt your are using and on which platform.



  • @SGaist
    Yes thank you, I will keep it in mind.
    I got a solution just now:
    I use the scrollBars. When the mouse is dragging, I change the scrollbars depending on the QMouseEvent x and y.
    Here is the implementation:

    void GraphWidget::mousePressEvent(QMouseEvent *event){
        if (event->button() == Qt::RightButton)
        {
            rightMousePressed = true;
            _panStartX = event->x();
            _panStartY = event->y();
            setCursor(Qt::ClosedHandCursor);
            event->accept();
            return;
        }
    }
    
    void GraphWidget::mouseReleaseEvent(QMouseEvent *event){
        if (event->button() == Qt::RightButton)
        {
            rightMousePressed = false;
            setCursor(Qt::ArrowCursor);
            event->accept();
            return;
        }
        event->ignore();
    }
    
    void GraphWidget::mouseMoveEvent(QMouseEvent *event){
        if (rightMousePressed)
        {
            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();
    
    }
    

    This is a very easy way to do this and I think it should work for everyone.
    I got the answer here: https://stackoverflow.com/questions/4753681/how-to-pan-images-in-qgraphicsview


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.