How to change the position of QGraphicsView content?

  • 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());
    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;

  • @Forfunckle
    What is "your own system"? Without understanding that, we will not be able to give you answers.

    My guess is that your boundingRect is wrong after using your scaling system.

  • @Asperamanca
    You're right, I forgot to say. Sorry!

    I'm just scaling the elements like that:

    for (int y = 0; y < canvasSize[0]; i++)
        for (int x = 0; x < canvasSize[1]; j++)
            pixels[y][x]->setRect(y*zoomLevel, x*zoomLevel, zoomLevel, zoomLevel);

    pixels is a matrix of rect items. I am changing their rects directly.

Log in to reply