Search code examples
c++qtcoordinatesqgraphicssceneqgraphicsitem

Convert QGraphicsItem::pos() to scene coordinates


I have a custom QGraphicsItem which overrides QGraphicsItem::itemChange() like so

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) is located where the item was created, while rect's (0, 0) is located at the top-left corner of the scene;

I would like to convert newPos so it lives in the same coordinate system as rect. I tried all the mapTo / mapFrom functions from QGraphicsItem, but nothing is working.

Could anybody help ? Thanks


Solution

  • Ok so I think that I have solved my problem. The thing that I forgot to mention is that my item was initialized this way:

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

    What I did to fix my problem is first initialize the item at (0, 0) and then use QGraphicsItem::moveBy() instead of giving positions to my item's constructor.

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

    Now newPos and rect give me the same coordinates in the itemChange() function.