首页 > 解决方案 > 获取可调整大小的选择区域的 QTransform

问题描述

我构建了一个小的自定义 qml 项目,用作选择区域(类似于Qt Widgets 中提供的QRubberBand组件)。该项目还使用户能够调整选择内容的大小,因此通过抓住选择矩形的底角,可以拖动以放大内容。用户完成调整大小后,我想计算转换的QTransform矩阵。QTransform提供了一个方便的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我的转换newSelectionRect在应用于selectionRect.

标签: c++qtqt5

解决方案


问题在于这个假设:

QTransform::scale 假设变换的中心点是物体的中心

QTransform 执行的所有变换都参考轴的原点,只是各种变换矩阵的应用(https://en.wikipedia.org/wiki/Transformation_matrix): 在此处输入图像描述

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

沿 x 轴移动坐标系 dx,沿 y 轴移动 dy,并返回对矩阵的引用。

因此,您正在寻找的是:

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!

推荐阅读