user336063
user336063

Reputation:

Rotate rectangle around its center

I need to rotate a rectangle around it's center-point and display it in the center of a QWidget. Can you complete this specific code? If possible, could you also dumb-down the explaination or provide a link to the simplest explaination?

Please note: I have read the Qt documentation, compiled examples/demos that deal with rotation and I STILL cannot understand it!

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));

}

Upvotes: 7

Views: 19818

Answers (2)

IMAN4K
IMAN4K

Reputation: 1345

Simple:

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());
}

Upvotes: 5

Arlen
Arlen

Reputation: 6835

 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));
  }

You are in the painter's coordinate system. When you call drawRect(x, y, 13, 17), it's upper left corner is at (x,y). If you want (x, y) to be the center of your rectangle, then you need to move the rectangle by half, hence rx and ry.

You can call resetTransform() to reset the transformations that were made by translate() and rotate().

Upvotes: 14

Related Questions