imulsion
imulsion

Reputation: 9040

Qt rotating shapes

I'm experimenting with drawing and rotating shapes in Qt, but I'm really at a loss as to how it works. Currently I have code which draws a rectangle with a small triangle on top of it. I want to rotate the shape by 35 degrees, so I try this:

void Window::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QBrush brush;
    brush.setStyle(Qt::SolidPattern);
    brush.setColor(Qt::white);
    painter.setBrush(brush);
    painter.setPen(Qt::NoPen);
    painter.fillRect(0,0,800,800,brush);
    brush.setColor(Qt::red);
    painter.translate(s.getX()-5,s.getY()-8);
    painter.rotate(35);
    painter.fillRect(0,0,10,16,brush);
    QPolygon pol;
    pol.setPoints(3,0,0,10,0,5,10);
    QPainterPath p;
    p.addPolygon(pol);
    painter.fillPath(p,brush);
}

(Ignore the s.getX/Y() calls, for now x is 150 and y is 750.)

Without the rotating and translating the code works fine and draws the shape. With the current code only the rectangle is displayed, not the polygon. How do I rotate these shapes?

Upvotes: 0

Views: 1436

Answers (1)

AMA
AMA

Reputation: 4214

You need to properly understand how affine transformations work. Without the proper understanding you will have hard times achieving what is needed.

  • rotate rotates everything around center of coordinates: (0,0)
  • translate moves center of coordinates to a new position

Your code rotates everything around the point (s.getX() - 5, s.getY() - 8).

So here's the code that will rotate both shapes 35 degrees around the center of red rectangle:

QPainter painter(this);
QBrush brush;
brush.setStyle(Qt::SolidPattern);
brush.setColor(Qt::white);
painter.setBrush(brush);
painter.setPen(Qt::NoPen);
painter.fillRect(0, 0, 800, 800, brush);
brush.setColor(Qt::red);
painter.translate(150, 750);

painter.translate(5, 8); // move center of coordinates to the center of red rectangle
painter.rotate(35); // rotate around the center of red rectangle
painter.translate(-5, -8); // move center of coordinates back to where it was

painter.fillRect(0, 0, 10, 16, brush);
QPolygon pol;
pol.setPoints(3, 0, 0, 10, 0, 5, 10);
QPainterPath p;
p.addPolygon(pol);
brush.setColor(Qt::blue);
painter.fillPath(p, brush);

Without transformations:

enter image description here

With transformations:

enter image description here

Upvotes: 2

Related Questions