Maybe I don't understand your issue. I thought you were trying to implement resizing of graphics items using resize handles on the bounding rectangles of the items.
What you implemented in your initial post works fine for rectangles and ellipses because they are defined by their bounding rectangles. Polygons and other items are defined by an arbitrary closed set of points connected by lines, but they do have a bounding rectangle, the smallest rectangle that contains all of the points. QPolygon (on which QGraphicsPolygonItem is based) has a constructor that takes a QRect argument, but that creates a rectangle polygon. That is the problem you ran into when you tried to implement the same code for resizing polygons that you used for the rectangle and ellipse.
The Wikipedia article I pointed you to shows how to construct a scale transformation using homogenous coordinates, which is what QTransform uses. Your resize code needs to look something like this (and of course you will add checks to avoid divide by zero):
float sx = float( rect.width() ) / float( boundingRect.width() );
float sy = float( rect.height() ) / float( boundingRect.height() );
QTransform transform;
transform.scale( sx, sy );
QPolygonF newPolygon
= oldPolygon
* transform;
item->setPolygon( newPolygon );
float sx = float( rect.width() ) / float( boundingRect.width() );
float sy = float( rect.height() ) / float( boundingRect.height() );
QTransform transform;
transform.scale( sx, sy );
QPolygonF oldPolygon = item->polygon();
QPolygonF newPolygon = oldPolygon * transform;
item->setPolygon( newPolygon );
To copy to clipboard, switch view to plain text mode
This code will change the aspect ratio. If you want to keep the same aspect ratio, then you will need to change one of the scale factors so that the new width and height preserve the same ratio as the old width and height.
But like I said earlier, the scale transformation scales the object around its (0,0) point. If the polygon's origin (0,0) is not at the center of the polygon, then scaling will probably also move it. If that happens to you, you will have to scale in three steps: translate your polygon to (0,0), scale, translate back. But by default, QGraphicsItem coordinates have the origin at their center (except for QGraphicsTextItem, QGraphicsPixmapItem, and maybe a few others that have their origin at topLeft).
Bookmarks