Search code examples
c++qtqgraphicsscene

Find the center position of a QGraphicsScene?


I have tried to use the following code to add a line to my scene:

    line = new QGraphicsLineItem(200,55,200,55);
    mscene.addItem(ruler);

But it seems the coordinate of the QGraphicsLineItem starts at the left corner. I don't want to alter the origin any way. I would like to just retrieve the center position's coordinate of the qgraphicsscene/qgraphicsview. What function should I use?


Solution

  • line = new QGraphicsLineItem(200,55,200,55);
    mscene.addItem(ruler);
    

    As the docs state for this constructor of QGraphicsLineItem: -

    Constructs a QGraphicsLineItem, using the line between (x1, y1) and (x2, y2) as the default line.

    This creates a QGraphicsLineItem with local coordinates of (200, 55, 200, 55), so the line that you're creating has the start and stop coordinates at the same point (200, 55).

    Once you create the line object and add it to the scene, you can then set its position with a call to setPos. To get the scene's centre position, you can use QGraphicsScene::width() and QGraphicsScene::height(): -

    // Assuming pScene is a pointer to the QGraphicsScene
    line->setPos(pScene->width()/2, pScene->height()/2);
    

    The QGraphicsView is just a window looking into a scene, so it can be smaller than the scene In this case, the item may be in the scene's centre, but not appear in the centre of the view.

    You can centre a view on an item with a call to QGraphicsView::centerOn(const QGraphicsItem * item)