Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing QGraphicsItem To Stay Put [duplicate]

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?

like image 494
rcv Avatar asked Apr 29 '11 03:04

rcv


2 Answers

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).

like image 177
user544511 Avatar answered Nov 13 '22 02:11

user544511


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.

like image 3
Arnold Spence Avatar answered Nov 13 '22 01:11

Arnold Spence