Important: Please read the Qt Code of Conduct -

Sample code for rotating

  • Hello.

    I am trying to make a simple example of rotating houses that I saw at this video: from 56:36.

    Can you please tell me is there any written form to that of similar code that I can look at. I tried to find any examples of that code because I learn the best when I look at some code, and in the video I cant do this.


  • All "QGraphicsView examples": might help you.
    If you're only looking for the perspective rotaton effect, see QTransform, and set a rotation that's not around the Z axis but e.g. X or Y. When QGraphicsView gets Rotations like that, it fakes a 3D effect by stretching/shearing the rotated objects.

  • Trick at this point is to move the rect to (0, 0) and then rotate:

    @class Widget : public QWidget
    Widget(QWidget *parent = 0) { }

    void paintEvent(QPaintEvent * event);


    void Widget::paintEvent(QPaintEvent * event)
    //rotate a rect around its middle point
    QPainter painter(this);

    QRect rect(150, 150, 200, 100);

    // this is hard-coded : the middle point of the rect is now real (0, 0) of painter's default window system
    QRect rect2(-100, -50, 200, 100);
    painter.translate(250, 200);

    static qreal degree = 0;
    QTimer::singleShot(1, this, SLOT(update()));


  • But if you want to rotate the point by yourself (which wont be easy), you can do something like this : ( hope helps :) )

    @void Widget::paintEvent(QPaintEvent * event)
    QPainter painter(this);
    static qreal degree = 0;

    QLine line(QPoint(100, 100), QPoint(199, 199));
    QPoint origin;
    origin.setX((line.p1().x() + line.p2().x())/2);
    origin.setY((line.p1().y() + line.p2().y())/2);
    // rotate point 1
    QPoint ptRotated1 = rotatePoint(degree, origin, line.p1());
    QPoint ptRotated2 = rotatePoint(degree, origin, line.p2());
    painter.drawLine(QLine(ptRotated1, ptRotated2));
    QTimer::singleShot(1, this, SLOT(update()));


    QPoint Widget::rotatePoint(int degree, QPoint origin, QPoint ptRotate) {

    double Pi = 3.14159265358979323846264338327950288419717;
    double rotAngle = degree * (Pi / 180.0);
    double sinAngle = qSin(rotAngle);
    double cosAngle = qCos(rotAngle);
    int px = ptRotate.x() - origin.x();
    int py = ptRotate.y() - origin.y();
    float xnew = px * cosAngle + py * sinAngle;
    float ynew = py * cosAngle - px * sinAngle;
    px = xnew + origin.x();
    py = ynew + origin.y();
    return QPoint(px, py);


Log in to reply