Greetings,

I'm using PyQt4 and trying to add a QGraphicsItem exactly in the center of the current screen, by clicking a menu button. So each click will add an item in the center of my screen.
My QGraphicsScene is very large (10k X 10K), so the QGraphicsView cannot show it entirely, there are scroll bars.

I can't find any function to return me the center point of my current screen, i searched in all QGraphicsScene and QGraphicsView functions.

There are functions to return the scene rect (it returns a rect 10k X 10k but it's useless) and there are functions to return the mouse position, but i need to move my mouse and click on a menu so the mouse will no longer be inside the scene and the item will be generated outside the visible space. And i also tried something with graphicsView.viewport().rect().center(), but it doesn't put my item in the center of the screen.

Thank you very much !

Dani AI

Generated

Good catch from : the visible center is a viewport coordinate, not a scene coordinate, so the correct approach is to map the viewport center into scene space and place the item there. The mapping handles scroll position and view transforms (scale/rotation), so it works even with a very large scene.

A compact PyQt4 example that centers an item by its geometry:

# view: QGraphicsView, item: QGraphicsItem (already created)
vp = view.viewport()
center_in_view = QPoint(vp.width() // 2, vp.height() // 2)
center_in_scene = view.mapToScene(center_in_view)

b = item.boundingRect()
item.setPos(center_in_scene - QPointF(b.width() / 2.0, b.height() / 2.0))

Notes and common pitfalls:

  • If the item uses transforms or has children, use item.sceneBoundingRect() to compute the true scene-size before offsetting.
  • For QGraphicsPixmapItem, setOffset(-w/2, -h/2) is an alternative to setPos(...) when centering the image origin.
  • mapToScene already accounts for view scaling/rotation; pick the specific QGraphicsView instance that is showing the content if multiple views share the scene.
  • To center the view on a newly added item instead of placing the item in the center, use view.centerOn(item).

This keeps the item visually centered without moving the mouse or changing the scene bounds.

If anyone is interested in the answer, that's it :

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

This returns the central point of current "screen".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.