沿直线旋转

问题描述 投票:0回答:1

qt中的第一个项目。

我无法沿直线平移/旋转矩形。基本上我想将rect与直线的位置对齐。当我更改圆的位置时,矩形应沿直线平移。参见下面的图片。

enter image description here

enter image description here

我现在有什么

w_len = len(str(weight)) / 3 * r + r / 3
weight_v = Vector(r if w_len <= r else w_len, r)
weight_rectangle = QRectF(*(mid - weight_v), *(2 * weight_v))
painter.drawRect(weight_rectangle)

* mid只是一个向量,其坐标在链接的一半处,weight_v是一个基于文本大小的向量。

任何指针,我应该看看向画家添加翻译吗?每当我尝试向画家添加平移时,它也会破坏其他形状。

t = QTransform()
t.translate(-5 ,-5)
t.rotate(90)
painter.setTransform(t)
painter.drawRect(weight_rectangle)
painter.resetTransform()

更新:

通过以下答案,我能够解决旋转问题。非常感谢,看来我的文字显示不正确。

enter image description here

我有以下代码:

painter.translate(center_of_rec_x, center_of_rec_y);
painter.rotate(- link_paint.angle());
rx = -(weight_v[0] * 0.5)
ry = -(weight_v[1] )
new_rec = QRect(rx , ry, weight_v[0], 2 * weight_v[1])
painter.drawRect(QRect(rx , ry, weight_v[0] , 2 * weight_v[1] ))
painter.drawText(new_rec, Qt.AlignCenter, str(weight))

Update2:

一切都很好,这是我的代码中的错误。我采用了错误的链接角度。

Thx。

python pyqt pyqt5
1个回答
1
投票

总是根据原点(0,0)进行旋转,因此需要平移到旋转的原点,然后应用它。

[此外,在对画家进行任何临时更改时,应使用save()restore():这样,将存储画家的当前状态,并且此状态将在以后恢复(包括在打印机中应用的任何转换)。与此同时)。画家状态可以嵌套,并且可以多次保存以应用画家状态修改的多个“层”。请记住,在释放(终止)绘画程序之前,必须将all状态恢复为基本状态。

由于您未提供MRE,所以我创建了一个小窗口小部件来显示其工作原理:

rectangle rotation example

class AngledRect(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.setMinimumSize(200, 200)

    def paintEvent(self, event):
        qp = QtGui.QPainter(self)
        qp.setRenderHints(qp.Antialiasing)

        contents = self.contentsRect()
        # draw a line from the top left to the bottom right of the widget
        line = QtCore.QLineF(contents.topLeft(), contents.bottomRight())
        qp.drawLine(line)

        # save the current state of the painter
        qp.save()
        # translate to the center of the painting rectangle
        qp.translate(contents.center())
        # apply an inverted rotation, since the line angle is counterclockwise
        qp.rotate(-line.angle())

        # create a rectangle that is centered at the origin point
        rect = QtCore.QRect(-40, -10, 80, 20)
        qp.setPen(QtCore.Qt.white)
        qp.setBrush(QtCore.Qt.black)
        qp.drawRect(rect)
        qp.drawText(rect, QtCore.Qt.AlignCenter, '{:.05f}'.format(line.angle()))
        qp.restore()

        # ... other painting...

对于简单的转换,使用translaterotate通常就足够了,但是上面的内容几乎与:]]

        transform = QtGui.QTransform()
        transform.translate(contents.center().x(), contents.center().y())
        transform.rotate(-line.angle())
        qp.save()
        qp.setTransform(transform)
        # ...
© www.soinside.com 2019 - 2024. All rights reserved.