Question

I have a QGraphicsScene with a QGraphicsPixmapItem on it, showing an image. I also have a view showing the scene. I have a mousePressEvent() function defined, looking for mouse clicks on the view.

The view is setup to contain the pixmap:

//pixmap is a QGraphicsPixmapItem *
view->fitInView(pixmap, Qt::KeepAspectRatio);

I can get the position of a mouse click in the view's coordinate system:

//e is my QMouseEvent *
QPoint local_pt = view->mapFromGlobal(e->globalPos());

Now I'd like to map this point to the original image coordinates, using any combination of the QGraphicsView, QGraphicsScene, QGraphicsPixmapItem

I've tried pixmap->boundingRect(), which gives me a QRectF(0,0 778x582), which has the appropriate dimensions (of the original image), but I do not see how the x and y coordinates are related to the local point of the click.

How do I get position of the mouse click in the original image coordinates?

EDIT:

This is what ultimately worked:

//e is my QMouseEvent *
QPoint  local_pt = view->mapFromGlobal(e->globalPos());
QPointF img_coord_pt = view->mapToScene(local_pt);

img_coord_pt is (0,0) when I click the top left corner of the image, and (image width, image height) at the bottom right corner.

Was it helpful?

Solution

QGraphicsView::mapToScene maps screen coordinates to scene coordinates, then use QGraphicsView::itemAt to get the item and QGraphicsItem::mapFromScene to map scene global coordinates to item local coordinates.

There are inverses of these, of course.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top