Search code examples
qtrotationpyqttransformqpainter

How to set transform origin for QPainter In Qt


I am using PyQt and more accurate QPainter for drawing a line. I need to rotate this line around an origin point (like clock handles), but setting it is not possible, I think! I found setTransformOriginPoint but it doesn't work for QPainter object. Setting origin point is not possible for QTransform and rotate that could affect QPainter object.

Also I tried rotating the line manually, using rotation equation and ..., this is the code:

def rotateLine(x, y, d):
    d = math.radians(d)
    x2 = x * math.cos(d) - y * math.sin(d)
    y2 = x * math.sin(d) + y * math.cos(d)
    return x2, y2
des = QPoint(400, 0)
for k in range(0, 10):
    paint.drawLine(center, des)
    newLine = rotateLine(des.x(), des.y(), 45)
    des = QPoint(newLine[0], newLine[1])
    logging.warning(des)

But it doesn't work correctly! What should I do?


Solution

  • I think one typical solution is to translate, rotate, and then draw. Here's a sample in C++ that will draw lines like hands on a clock with center at (50, 50) and extending from radius=0 to radius=400, with 45° between them.

    QPainter painter(this);
    painter.save();
    painter.translate(50, 50);  // Center
    for (int k = 0; k < 10; k++) {
        painter.drawLine(0, 0, 400, 0);
        painter.rotate(45);     // Degrees
    }
    painter.restore();
    

    Side note: Your rotateLine() function is correct for rotating the given point about the origin but it looks like you wanted it to rotate it about center. You could also get the desired effect by changing your call to drawLine to paint.drawLine(center, center + des).