How to efficiently get position of a QGraphicsItem in view coordinates?
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?
Re: How to efficiently get position of a QGraphicsItem in view coordinates?
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.
Re: How to efficiently get position of a QGraphicsItem in view coordinates?
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:
Code:
{
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.
Re: How to efficiently get position of a QGraphicsItem in view coordinates?
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:
Code:
QRectF itemBR
= item
->boundingRect
();
QRectF sceneBR
= item
->mapToScene
(itemBR
);
QRectF viewBR
= view
->mapFromScene
(sceneBR
);
// viewBR is your rect/point/whatever