PDA

View Full Version : How to efficiently get position of a QGraphicsItem in view coordinates?



wayfaerer
7th February 2012, 23:41
I'm trying to get the position in view coordinates of QGraphicsItems. I know that I can call QGraphicsItem::pos() followed by QGraphicsView::mapFromScene(). This seems inefficient, though, because the view coordinates had to be calculated in order to draw the item on the screen, so mapping the item from scene to view just to get the coordinates seems like double the work. Is there a more direct way?

wysota
8th February 2012, 00:58
No, view coordinates don't have to be calculated as the transformation is inherited from the parent item. So this is the most direct way.

wayfaerer
8th February 2012, 01:49
Oh ok. Just so I understand you correctly, QGraphicsView::mapFromScene just returns a coordinate, it doesn't actually have to "map" it first? I had a look at the source and it looks like it is being mapped, though I could be wrong:


QPoint QGraphicsView::mapFromScene(const QPointF &point) const
{
Q_D(const QGraphicsView);
QPointF p = d->identityMatrix ? point : d->matrix.map(point);
p.rx() -= d->horizontalScroll();
p.ry() -= d->verticalScroll();
return p.toPoint();
}

EDIT: I realized I misunderstood you. So it does map it, and that's the most direct way. Bummer. Well, thanks for letting me know.

wysota
8th February 2012, 01:57
Sure it has to map it. And using mapToScene() will only work if your item doesn't have a parent item.

A general approach is to use the following sequence:


QRectF itemBR = item->boundingRect();
QRectF sceneBR = item->mapToScene(itemBR);
QRectF viewBR = view->mapFromScene(sceneBR);// viewBR is your rect/point/whatever