I have a QGraphicsScene
that is filled with QGraphicsItems
, and the user is able to pan and zoom around to inspect all of the various QGraphicsItems
. However, I would like to have a QGraphicsTextItem
label that always stays put at the top left of the screen. Ignoring the zooms is easy, as I can just setFlags(QGraphicsItem::ItemIgnoresTransformations)
, but I've yet to figure out how to force the position to stay at the top-left. What's the best way to make my label "float" in the same place?
I think the only (realiable) way to do that is to recalculate position for your text item every frame. To do this, simply subclass QGraphicsView, override paintEvent and use QGraphicsView::mapToScene() to calculate new position. Something like:
void MyGraphicsView::paintEvent(QPaintEvent*)
{
QPointF scenePos = mapToScene(0,0); // map viewport's top-left corner to scene
m_textItem->setPos(scenePos);
}
I have done this many many times and it has worked very well.
Of course you could just create normal QLabel like Arnold Spence mentions in his answer. However, this won't work in many situations (e.g. if you really want to place label on top of graphics view and you are using OpenGL-accelerated viewport).
Perhaps you just want to put a regular QLabel
right on the view instead of trying to make a part of the scene stay in one place as discussed in this question.
Note: As mentioned in another answer, this trick will often not work with hardware accelerated views. In these cases, you will need to make the text items a part of the scene.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With