我想在PyQT4中以左下角的给定角度旋转QRectF。我知道如何绘制一个矩形,但我仍然坚持如何旋转它。我尝试使用rotate(),但是顺时针旋转坐标系给定的角度。
是否有任何简单的解决方案(通过更改坐标绘制多边形除外)?
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()
答案 0 :(得分:1)
您可以通过painter.translate()
将旋转中心(始终左上角)移动到窗口小部件的任意点,在旋转中心绘制左上角的矩形,计算x和y偏移量您想要的旋转中心并再次移动对象,然后旋转下一个对象的坐标系。这里是pyqt5中的一个工作示例,用QtGui代替QtWidgets 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_())
看起来像这样: