- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 331字
- 2021-08-27 18:31:02
What just happened?
Most transformations depend on the origin point of the coordinate system. For rotation and scaling, the origin point is the only point that remains in place. In the preceding example, we used a rectangle with the top-left corner at (50, 50) and the size of (50, 50). These coordinates are in the item's coordinate system. Since we originally didn't move the item, the item's coordinate system was the same as the scene's coordinate system, and the origin point is the same as the scene's origin (it's the point marked with the cross). The applied rotation uses (0, 0) as the center of rotation, thus providing an unexpected result.
There are multiple ways to overcome this problem. The first way is to change the transform's origin point:
QGraphicsRectItem* rectItem = scene.addRect(50, 50, 50, 50); rectItem->setTransformOriginPoint(75, 75); rectItem->setRotation(45);
This code produces the rotation we want, because it changes the origin point used by the setRotation() and setScale() functions. Note that the item's coordinate system was not translated, and (75, 75) point continues to be the center of the rectangle in the item's coordinates.
However, this solution has its limitations. If you use setTransform() instead of setRotation(), you will get the unwanted result again:
QGraphicsRectItem* rectItem = scene.addRect(50, 50, 50, 50); rectItem->setTransformOriginPoint(75, 75); QTransform transform; transform.rotate(45); rectItem->setTransform(transform);
Another solution is to set up the rectangle in such a way that its center is in the origin of the item's coordinate system:
QGraphicsRectItem* rectItem = scene.addRect(-25, -25, 50, 50); rectItem->setPos(75, 75);
This code uses completely different rectangle coordinates, but the result is exactly the same as in our first example. However, now, (75, 75) point in the scene's coordinates corresponds to (0, 0) point in the item's coordinates, so all transformations will use it as the origin:
QGraphicsRectItem* rectItem = scene.addRect(-25, -25, 50, 50); rectItem->setPos(75, 75); rectItem->setRotation(45);