【问题标题】:Convert QGraphicsItem::pos() to scene coordinates [closed]将 QGraphicsItem::pos() 转换为场景坐标
【发布时间】:2021-09-29 17:29:47
【问题描述】:

我有一个自定义的QGraphicsItem,它会像这样覆盖QGraphicsItem::itemChange()

QVariant CustomItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemPositionChange) {
        QPointF newPos = value.toPointF();
        QRectF rect = mapRectToScene(boundingRect());

        qDebug() << "newPos" << newPos;
        qDebug() << "rect" << rect;
    }
    return QGraphicsItem::itemChange(change, value);
}

newPos's (0, 0) 位于创建项目的位置,而rect's (0, 0) 位于场景左上角;

我想转换newPos,使其与rect 位于同一坐标系中。 我尝试了 QGraphicsItem 中的所有 mapTo / mapFrom 函数,但没有任何效果。

有人可以帮忙吗?谢谢

【问题讨论】:

  • newPos 不在项目的坐标中,而是在场景的坐标中,所以我看不到必要的转换
  • @eyllanesc 以及我移动项目时我可以清楚地看到 newPos 和 rect 不显示相同的坐标...例如在第一次更改时, newPos 在 (0, 0) 但是rect 位于 (70, 70),所以当我移动项目时,rect 位于 (0, 0),newPos 位于 (-70, -70)。
  • Just boundingRect) 位于项目的坐标中,而 pos 位于场景的坐标中
  • 好的,我想我解决了我的问题,请看我的回答。谢谢你的帮助

标签: c++ qt coordinates qgraphicsscene qgraphicsitem


【解决方案1】:

好的,我认为我已经解决了我的问题。我忘了提到的是我的项目是这样初始化的:

auto item = new CustomItem(QPolygonF(QRectF(70, 70, 100, 100)));

我解决问题的方法是首先在 (0, 0) 处初始化项目,然后使用 QGraphicsItem::moveBy() 而不是为项目的构造函数提供位置。

auto item = new CustomItem(QPolygonF(QRectF(0, 0, 100, 100)));
item->moveBy(70, 70);

现在newPosrectitemChange() 函数中给我相同的坐标。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2019-02-14
    • 1970-01-01
    相关资源
    最近更新 更多