强制 QGraphicsItem 保持原状

发布于 2024-11-04 16:30:01 字数 261 浏览 3 评论 0原文

我有一个充满了 QGraphicsItems 的 QGraphicsScene,用户可以平移和缩放来检查所有不同的 QGraphicsItems。但是,我希望有一个始终位于屏幕左上角的 QGraphicsTextItem 标签。忽略缩放很容易,因为我只需 setFlags(QGraphicsItem::ItemIgnoresTransformations) 即可,但我还没有弄清楚如何强制位置保持在左上角。让我的标签“浮动”在同一个地方的最佳方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

客…行舟 2024-11-11 16:30:01

我认为唯一(可靠)的方法是每帧重新计算文本项的位置。为此,只需子类化 QGraphicsView,重写 PaintEvent 并使用 QGraphicsView::mapToScene() 来计算新位置。比如:

void MyGraphicsView::paintEvent(QPaintEvent*)
{
    QPointF scenePos = mapToScene(0,0); // map viewport's top-left corner to scene
    m_textItem->setPos(scenePos);
}

我已经这样做过很多次了,而且效果很好。

当然,您可以像 Arnold Spence 在他的回答中提到的那样创建普通的 QLabel。然而,这在很多情况下都不起作用(例如,如果您确实想将标签放置在图形视图之上并且您正在使用 OpenGL 加速视口)。

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

无名指的心愿 2024-11-11 16:30:01

也许您只是想在视图上放置一个常规的 QLabel,而不是像 这个问题

注意:正如另一个答案中提到的,这个技巧通常不适用于硬件加速视图。在这些情况下,您需要使文本项成为场景的一部分。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文