【问题标题】:Getting the QTransform of a resizable selection area获取可调整大小的选择区域的 QTransform
【发布时间】:2020-08-30 22:05:59
【问题描述】:

我已经构建了一个小的自定义 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,当应用于selectionRect 时返回newSelectionRect

【问题讨论】:

  • 您能否提供最小的可重现示例?
  • @Robert.K 我用一个小例子更新了我的帖子,说明我需要什么。
  • 你得到了什么而不是newSelectionRect
  • @Robert.K 它写在我的问题中。我得到QRectF selectionRect = QRectF(QPointF(10,10)*sx, QPointF(200,100)*sy);,其中sxsy 是两个矩形的宽度和高度之间的比率。

标签: c++ qt qt5


【解决方案1】:

问题在于这个假设:

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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-27
    • 2011-11-02
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    相关资源
    最近更新 更多