围绕其中心旋转矩形

时间:2011-12-21 06:52:07

标签: c++ qt

我需要围绕它的中心点旋转一个矩形并将其显示在QWidget的中心。你能完成这个特定的代码吗?如果可能的话,您是否也可以对解释进行愚蠢的解释或提供最简单解释的链接?

请注意:我已经阅读了Qt文档,编译了处理轮换的示例/演示,而我仍然无法理解!

void Canvas::paintEvent(QPaintEvent *event)
{
    QPainter paint(this);

    paint.setBrush(Qt::transparent);
    paint.setPen(Qt::black);
    paint.drawLine(this->width()/2, 0, this->width()/2, this->height());
    paint.drawLine(0, this->height()/2, this->width(), this->height()/2);

    paint.setBrush(Qt::white);
    paint.setPen(Qt::blue);

    // Draw a 13x17 rectangle rotated to 45 degrees around its center-point
    // in the center of the canvas.

    paint.drawRect(QRect(0,0, 13, 17));

}

2 个答案:

答案 0 :(得分:10)

 void paintEvent(QPaintEvent* event){
    QPainter painter(this);

    // xc and yc are the center of the widget's rect.
    qreal xc = width() * 0.5;
    qreal yc = height() * 0.5;

    painter.setPen(Qt::black);

    // draw the cross lines.
    painter.drawLine(xc, rect().top(), xc, rect().bottom());
    painter.drawLine(rect().left(), yc, rect().right(), yc);

    painter.setBrush(Qt::white);
    painter.setPen(Qt::blue);

    // Draw a 13x17 rectangle rotated to 45 degrees around its center-point
    // in the center of the canvas.

    // translates the coordinate system by xc and yc
    painter.translate(xc, yc);

    // then rotate the coordinate system by 45 degrees
    painter.rotate(45);

    // we need to move the rectangle that we draw by rx and ry so it's in the center.
    qreal rx = -(13 * 0.5);
    qreal ry = -(17 * 0.5);
    painter.drawRect(QRect(rx, ry, 13, 17));
  }

你是画家的坐标系。当你调用drawRect(x,y,13,17)时,它的左上角是(x,y)。如果您希望(x, y)成为矩形的中心,则需要将矩形移动一半,因此rxry

您可以致电resetTransform()重置translate()rotate()所做的转化。

答案 1 :(得分:0)

简单:

void rotate(QPainter* p, const QRectF& r, qreal angle, bool clock_wise) {
    p->translate(r.center());
    p->rotate(clock_wise ? angle : -angle);
    p->translate(-r.center());
}