Nominate our 2022 Qt Champions!

Force QGraphicsView size to match QGraphicsScene size

  • I use the following code to set the size of my QGraphicsScene and my QGraphicsView:
    view->setFixedSize(width, height);
    view->setSceneRect(0, 0, width, height);

    However, my view is always just about 90% the size of the scene which results in always having scroll bars. How can I force my QGraphicsView to be the exact same size as the QGraphicsScene?

    ~ Tectu

  • Try one of the "QGraphicsView::fitInView":
    Also you can modify scroll bars policy.

  • Thank you very much for your suggestion. The following code does exactly what I wanted:

    view->setFixedSize(width, height);
    view->setSceneRect(0, 0, width, height);
    view->fitInView(0, 0, width, height, Qt::KeepAspectRatio);

  • Well, for some reason the "coordinate resolution" is not quite right after calling QGraphicsView::fitInView. When I place an item at 0/0 it is not at the border.

    How can I make sure that resolution of the coordinates of my items is pixel-vise? So an item placed at (13, 37) will begin at pixel (13,37).

  • As the documentation of QGraphicsView::fitInview suggests one can use @QGraphicsView::setVerticalScrollBarProperty(Qt::ScrollBarAlwaysOff);@ to make sure that the entire scene fits the view.

    Therefore, the following code works for my case:
    @view->setFixedSize(width, height);
    view->setSceneRect(0, 0, width, height);

    Thank you again for your help.

  • Hi !

    I know this topic is old, but as it appears among top suggestions on Google when you're looking for answers about how to adapt the GraphicsView to the GraphicsScene, I answer it directly so that other people trying to fix this problem see the more accurate answer I've written.

    Forcing the absence of scrollbars does not actually solve the problem, because you do not see the entire scene. If scrollbars appear, it means that the scene is larger than the view.
    The default parameter of scrollbars (Qt::ScrollBarAsNeeded) is really well managed by the framework, so I suggest that you keep it as it is, the problem lies elsewhere.
    So, the problem lies in the automatic borders displayed on the GraphicsView because they are taken into account in the calculation of the size of the GraphicsView, and their default width is 1px. This means that two pixels in width and two pixels in height of your GraphicsScene are covered by you GraphicsView, so logically, scrollbars appear to enable you to get access to your whole scene.

    Now, you have two proper solutions :

    1. You do not want the borders, add the line :

    2. You want to keep the borders, so modify the setFixedSize parameters like this :
      yourGraphicsView->setFixedSize(width+2*yourGraphicsView->frameWidth(), height+2*yourGraphicsView->frameWidth());

    I hope it will help you ! :)

  • @Proteos This was a great help. Thanks!

Log in to reply