获取可调整大小的选择区域的 QTransform

Getting the QTransform of a resizable selection area

我已经构建了一个用作选择区域的小型自定义 qml 项目(类似于 QRubberBand component provided in Qt Widgets). The item also give the ability to user to resize the content of the selection, so by grabbing the bottom corner of the selection rectangle it is possible to drag to enlarge the content. After the user has done resizing I would like to compute the QTransform matrix of the transformation. QTransform provides a convenient QTransform::scale 方法来获取比例变换矩阵(我可以通过比较宽度和高度比率与选择的先前大小)。问题是 QTransform::scale 假设变换的中心点是对象的中心,但我希望我的变换原点是选择的左上角(因为用户从右下角拖动)。

例如,如果我有以下代码:

QRectF selectionRect = QRectF(QPointF(10,10), QPointF(200,100));

// let's resize the rectangle by changing its bottom-right corner
auto newSelectionRect = selectionRect;
newSelectionRect.setBottomRight(QPointF(250, 120));

QTransform t;
t.scale(newSelectionRect.width()/selectionRect.width(), newSelectionRect.height()/selectionRect.height());

这里的问题是,如果我将转换 t 应用到我原来的 selectionRect 我没有得到我的新矩形 newSelectionRect ,但我得到以下信息:

QRectF selectionRect = QRectF(QPointF(10,10)*sx, QPointF(200,100)*sy);

其中 sxsy 是变换的比例因子。我想要一种方法来计算我的转换的 QTransform 当应用于 selectionRect.

时返回 newSelectionRect

问题出在这个假设上:

QTransform::scale assumes that the center point of the transformation is the center of the object

QTransform的所有变换都以轴为原点,只是各种变换矩阵的应用(https://en.wikipedia.org/wiki/Transformation_matrix):

此外,QTransform::translate (https://doc.qt.io/qt-5/qtransform.html#translate) 指出:

Moves the coordinate system dx along the x axis and dy along the y axis, and returns a reference to the matrix.

因此,您正在寻找的是:

QTransform t;
t.translate(+10, +10); // Move the origin to the top left corner of the rectangle
t.scale(newSelectionRect.width()/selectionRect.width(),  newSelectionRect.height()/selectionRect.height()); // scale
t.translate(-10, -10); // move the origin back to where it was

QRectF resultRect = t.mapRect(selectionRect); // resultRect == newSelectionRect!