QRect 是如何工作的?

问题描述 投票:0回答:1
std::vector<QPoint> points;
points.push_back({3, 1});
points.push_back({6, 1});
points.push_back({6, 4});
points.push_back({3, 4});

QRect rect(points[0], QSize{points[1].x() - points[0].x(), points[2].y() - points[1].y()});

qDebug() << rect << rect.topLeft() << rect.topRight() << rect.bottomRight() << rect.bottomLeft() << rect.width() << rect.height();

以上打印:

QRect(3,1 3x3) QPoint(3,1) QPoint(5,1) QPoint(5,3) QPoint(3,3) 3 3

上面的内容对我来说似乎很奇怪。看来

(6,1)
已移至
(5.1)
。其他职位也发生了类似的情况。

宽度

3
怎么样?不是应该是
5 - 3
(右上角 - 左上)吗?

来自 QRect 文档:

还有第三个构造函数,它使用左上角和右下角坐标创建 QRect,但我们建议您避免使用它。其基本原理是,由于历史原因,bottom() 和 right() 函数返回的值偏离了矩形的真实右下角。

这对我来说并没有澄清。

c++ qt rectangles
1个回答
0
投票

QRect::right()
尝试返回矩形内的最后一个像素,例如:

int right = rect.left() + rect.width() - 1;

Q_ASSERT(rect.right() == right);

当然,

QRect::bottom()
的工作原理类似。

如果不需要这种行为,那么您可以使用

QRectF
类代替,或者始终手动执行:

int right = rect.left() + rect.width();
© www.soinside.com 2019 - 2024. All rights reserved.