Search code examples
c++qtqgraphicsviewqgraphicsscene

Why do the first added item always appear at the center in a graphics scene/view in Qt?


I have a graphics scene and view, and then I'm adding a single element. But no matter what x/y coordinate I give, it always appears at the center of the graphics view.

Why does this happen, and how can I make it appear at, say, the upper left corner?

This is my code:

scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
QGraphicsEllipseItem *ellipseItem = scene->addEllipse(150, 150, 10, 10);

Solution

  • The reason for this is that by default, QGraphicsScene computes its sceneRect by adding all the item rectangles together. When you add the first item, it automatically uses it as the scene rect. And by default QGraphicsView scales and centers on the scene rect.

    If you know the final or desired scene rect, set it before you add any item:

    scene->setSceneRect(0, 0, 800, 600);
    scene->addEllipse(150, 150, 10, 10);