- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 442字
- 2021-08-27 18:31:03
Conversions between coordinate systems
If an item is simply moved using setPos(), conversion from the item's coordinates to the scene coordinates is as simple as sceneCoord = itemCoord + item->pos(). However, this conversion quickly becomes very complex when you use transformations and parent–child relationships, so you should always use dedicated functions to perform such conversions. QGraphicsItem provides the following functions:
Function | Description |
|
Maps the point point that is in the item's coordinate system to the corresponding point in the scene's coordinate system. |
scenePos() |
Maps the item's origin point to the scene's coordinate system. This is the same as mapToScene(0, 0). |
sceneBoundingRect() |
Returns the item's bounding rectangle in the scene's coordinate system. |
mapFromScene( |
Maps the point point that is in the scene's coordinate system to the corresponding point in the item's coordinate system. This function is the reverse function to mapToScene(). |
mapToParent( |
Maps the point point that is in the item's coordinate system to the corresponding point in the coordinate system of the item's parent. If the item does not have a parent, this function behaves like mapToScene(); thus, it returns the corresponding point in the scene's coordinate system. |
mapFromParent( |
Maps the point point that is in the coordinate system of the item's parent to the corresponding point in the item's own coordinate system. This function is the reverse function to mapToParent(). |
mapToItem( |
Maps the point point that is in the item's own coordinate system to the corresponding point in the coordinate system of the item item. |
mapFromItem( |
Maps the point point that is in the coordinate system of the item item to the corresponding point in the item's own coordinate system. This function is the reverse function to mapToItem(). |
What is great about these functions is that they are not only available for QPointF. The same functions are also available for QRectF, QPolygonF, and QPainterPath, not to mention that there are some convenience functions:
- If you call these functions with two numbers of the qreal type, the numbers are interpreted as the x and y coordinates of a QPointF pointer
- If you call the functions with four numbers, the numbers are interpreted as the x and y coordinates and the width and height of a QRectF parameter
The QGraphicsView class also contains a set of mapToScene() functions that map coordinates from the viewport's coordinate system to the scene coordinates and mapFromScene() functions that map the scene coordinates to the viewport coordinates.