Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Changing the position of QGraphicsView content



  • I am reposting this question because the original didn't get answers.

    I have the following situation: there are some QGraphicsItems in my QGraphicsScene. When I add them to the scene, they look nice and centered. Afterwards, I have a zoom system which scales up my elements individually, instead of QGraphicsView::scale() (which I do not want to use because it doesn't work for what I need). Thing is, when I zoom in, it works, but when I zoom out, it's not centering in the center of the items, but at the top left corner of the items. Here is what I mean:

    What i want

    I would like it to stay in the center. I am also already using centerOn(), but it only works when I use QGraphicsView::scale() instead of my own system. How can I make it work? Here is the code that gets executed after my zoom:

    // ...
    // scaling the elements here
    // ...
    QPointF delta = target_viewport_pos - mouse_event->pos();
    if (qAbs(delta.x()) > 5 || qAbs(delta.y()) > 5) {
        target_viewport_pos = mouse_event->pos();
        target_scene_pos = _view->mapToScene(mouse_event->pos());
    }
    _view->centerOn(target_scene_pos);
    QPointF delta_viewport_pos = target_viewport_pos - QPointF(_view->viewport()->width() / 2.0,
                                                               _view->viewport()->height() / 2.0);
    QPointF viewport_center = _view->mapFromScene(target_scene_pos) - delta_viewport_pos;
    _view->centerOn(_view->mapToScene(viewport_center.toPoint()));
    

  • Lifetime Qt Champion

    @Forfunckle Isn't this same question as https://forum.qt.io/topic/115568/how-to-change-the-position-of-qgraphicsview-content ?
    Please do not double post!
    Closing...


Log in to reply