开发者

Forcing QGraphicsItem To Stay Put [duplicate]

开发者 https://www.devze.com 2023-03-02 00:40 出处:网络
This question already has an answer here: Draw an item in a static location relative to the QGraphicsView
This question already has an answer here: Draw an item in a static location relative to the QGraphicsView (1 answer) Closed 9 years ago. 开发者_如何学Python

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消