Search code examples
qtviewportqgraphicsview

why QGraphicsView mapFromScene return difference point depending on when to call view.show()?


I want to get view's coordinate of scene's origin point (0,0). But I could not figure it out reason for the strange return of QGraphicsView::mapFromScene(). Depend on when I call QGraphicView::show() (1.before adding scene to view; 2.after adding scene to view but before item added to scene; 3.after scene and item added), the result is different.

QGraphicsView view;
QGraphicsScene scene;

//    1. view.show(); ---> view.mapToScene(QPoint(0,0)) return (127,95)

view.setScene(&scene);

//    2. view.show(); ---> view.mapFromScene(QPoint(0,0)) return (99,49)

scene.addRect(0,0,300,300, QPen(QColor(Qt::red)));
view.update();

//    3. view.show(); ---> view.mapToScene(QPoint(0,0)) return (0,0) which seem 
      to be the only correct one.

qDebug() << view.mapToScene(QPoint(0,0));

Solution

  • That's expected. At #1, there's no scene, so any notion of mapping is void anyway. You can get any and all results. At #2, the scene has no bounding rectangle, and is thus probably mapped at 1:1 centered - the mapping is not useful anyway at this point, since there's nothing to map from (empty scene!). At #3 there finally is something in the scene, and the mapping has an expected value.