QGraphicsRotation to QRectF?

1k Views Asked by At

I want to rotate QRectF in PyQT4 by given angle around bottom left corner. I know how to draw a rectangle but I'm stuck on how to rotate it. I tried with rotate(), but it rotates the coordinate system the given angle clockwise.

Is there any easy solution (except drawing a Polygon by changing coordinates)?

margin = 10
width = 100
depth = 20
self.p = QPainter(self)
self.rectangle = QRectF(margin, margin, width, depth)
self.angle = 30
self.p.rotate(self.angle)
self.p.drawRect(self.rectangle)
self.p.end()
1

There are 1 best solutions below

0
On

you can move the rotation center (always top left corner) to an arbitrary point of the widget by painter.translate(), paint the rectangle with top left corner in the rotation center, calculate the x- and y- offset of your wanted rotation center and move the object again, then rotate the coordinate system for the next object. here a working example in pyqt5, replace QtWidgets by QtGui for pyqt4:

import sys 
import math
from PyQt5 import QtCore, QtGui, QtWidgets

class MeinWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setGeometry(200,50,300,300)
        self.pen1 = QtGui.QPen(QtGui.QColor(0,0,0))
        self.pen2 = QtGui.QPen(QtGui.QColor(255,0,0))
        self.pen3 = QtGui.QPen(QtGui.QColor(0,255,0))
        self.pen4 = QtGui.QPen(QtGui.QColor(0,0,255))
        self.brush = QtGui.QBrush(QtGui.QColor(255,255,255))

        self.pens = (self.pen1, self.pen2, self.pen3, self.pen4)
        self.rw = 100
        self.rh = 50

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.translate(QtCore.QPointF(self.rw,self.rh))      # move rotation center to an arbitrary point of widget
        angle = 10
        for i in range(0,len(self.pens)):
            dy = self.rh - self.rh*math.cos(math.radians(angle))    # vertical offset of bottom left corner
            dx = self.rh*math.sin(math.radians(angle))          # horizontal offset of bottom left corner
            p = self.pens[i]
            p.setWidth(3)
            painter.setPen(p)
            painter.drawRect(0,0,self.rw,self.rh)
            painter.translate(QtCore.QPointF(dx,dy))            # move the wanted rotation center to old position 
            painter.rotate(angle)
            angle += 10

app = QtWidgets.QApplication(sys.argv)      
widget = MeinWidget()
widget.show()
sys.exit(app.exec_())

looks like this:

rotation of a rectangle around bottom left