Nyaruko
Nyaruko

Reputation: 4459

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?

Upvotes: 1

Views: 6092

Answers (2)

mots_g
mots_g

Reputation: 637

You can do a mapping between the coodrinate system. To get the center of screen in scene co-ordiantes, calculate the center of the viewport and then do a mapToScene:

myView.mapToScene(myView.viewport()->rect().center()) 

You may read more about the co-ordinate mapping at: [https://doc.qt.io/archives/4.6/graphicsview.html#item-coordinates][1]

Upvotes: 3

TheDarkKnight
TheDarkKnight

Reputation: 27611

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)

Upvotes: 3

Related Questions