警惕QRect::top()函數,以及QSize

在前面的博客《自己對QLineF::angle()的理解 》裏,我提到了QWidget的Y軸指向向下。這樣的情況同樣發生在QRect等幾何形狀上。QRect::top()的字面意思是矩形上沿的縱座標。我們往往會認爲其返回值等於矩形四個頂點裏縱座標最大的那個值。然而,由於Qt對Y方向的規定,top返回的其實是較小的值。來看下面的例子:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRect>
#include <QPolygon>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QPoint pnt1(ui->spinBox->value(), ui->spinBox_2->value()),
            pnt2(ui->spinBox_3->value(), ui->spinBox_4->value()),
            pnt3(ui->spinBox_5->value(), ui->spinBox_6->value()),
            pnt4(ui->spinBox_7->value(), ui->spinBox_8->value());

    QPolygon plgn;
    plgn<<pnt1<<pnt2<<pnt3<<pnt4;

    QRect rct = plgn.boundingRect();

    int i = rct.top();
    ui->spinBox_9->setValue(i);
}

效果:

對於由(0,0), (0,1), (1,0), (1,1)圍成的矩形,top = 0

對於由(0,-1), (0,1), (1,-1), (1,1)圍成的矩形,top = -1

可見,top返回的是Y方向較小的點的縱座標。

 

沿着這個思路走下去,考慮如何運用QRect的構造函數。QRect有多種構造函數,其中一種的語法是這樣的

QRect(QPoint, QSize())

qSize::height 的含義值得注意。當height爲正時,說明QRect::bottom > QRect:top

來看下面的代碼:

可見,當height爲正時,說明QRect::bottom > QRect:top

另外,有人注意到bottom == 9, height == 9而不是10.QT的文檔對此給出瞭解釋:

int QRect::bottom() const

Returns the y-coordinate of the rectangle's bottom edge.

Note that for historical reasons this function returns top() + height() - 1; use y() + height() to retrieve the true y-coordinate.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章