Search code examples
c++qtqgraphicsitem

How to map item coordinates?


I know that every item has own coordinates relative to scene. I am adding an ellipse in the scene. Each of them returns the following from boundingRect(): QRect(0, 0, 50, 50). I don't know how to map coordinates to another QGraphicsItem which is a line. The line supposed to connect this two ellipses. I have correct coordinates of ellipses and I am passing them to a custom QGraphicsLineItem constructor. However the line is in a wrong place. How should I use mapFromItem() or other method to get the result?

I get each ellipse's coordinates as follows:

selfCoords = ellipse->mapFromScene(QPointF(0.0,0.0));

Solution

  • You should map the coordinates from each ellipse to some common coordinate system that you can then map to the line's parent. The common coordinate system can be the scene's coordinate system.

    For example, to connect the centers of the ellipses:

    QGraphicsScene scene;
    QGraphicsEllipseItem e1, e2;
    scene.addItem(&e1);
    scene.addItem(&e2);
    ... // set the ellipse rects/sizes
    auto start = e1.mapToScene(e1.boundingRect().center());
    auto end = e2.mapToScene(e2.boundingRect().center());
    QGraphicsLineItem l(QLineF(start, end));
    scene.addItem(&l);
    

    You can do this because the line's parent is the scene. Now assume that we had some other parent for the line - you'd need to map the coordinates to that parent instead.

    ...
    QGraphicsItem p;
    p(20, 20);
    scene.addItem(&p);
    auto start = e1.mapToItem(&p, e1.boundingRect().center());
    auto end = e2.mapToItem(&p, e2.boundingRect().center());
    QGraphicsLineItem l(QLineF(start, end), &p);