QGraphicsPixmapItem无法正确旋转

问题描述

我需要将QGraphicsPixmapItem旋转一圈。也就是说,圆圈必须始终位于图像的左上角,并且当我拖动圆圈时,图像必须旋转。我使用setRotation设置旋转角度,并使用setTransformOriginPoint设置旋转点。但是,旋转效果不佳。有人可以指出我正确的方向吗?

import sys
from PyQt5.QtWidgets import QMainWindow,QApplication,QGraphicsView
from PyQt5 import QtGui,QtWidgets,QtCore
import math

class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)

        self.scene = Scene()
        self.view = QGraphicsView(self)
        self.setGeometry(10,30,850,600)
        self.view.setGeometry(20,22,800,550)
        self.setFixedSize(850,600)
        self.view.setScene(self.scene)

class Scene(QtWidgets.QGraphicsScene):
    def __init__(self,parent=None):
        super(Scene,self).__init__(parent)
        # other stuff here
        self.set_image()

    def set_image(self):
        image = Image()
        self.addItem(image)
        image.set_pixmap()

class Image(QtWidgets.QGraphicsPixmapItem):
    def __init__(self,parent=None):
        super(Image,self).__init__(parent)

        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable,True)
        self.setTransformOriginPoint(self.boundingRect().center())

    def set_pixmap(self):
        pixmap = QtGui.QPixmap("image.jpg")
        self.setPixmap(pixmap)
        self.pixmap_controller = PixmapController(self)
        self.pixmap_controller.set_pixmap_controller()

class PixmapController(QtWidgets.QGraphicsEllipseItem):
    def __init__(self,pixmap):
        super(PixmapController,self).__init__(parent=pixmap)
        self.pixmap = pixmap

        color = QtGui.QColor(0,0)
        brush = QtGui.QBrush(color)
        self.setBrush(brush)

    def set_pixmap_controller(self):
        self.setRect(-5,-5,10,10)

    def mousePressEvent(self,event):
        if event.button() == QtCore.Qt.LeftButton:
            self.startPos = event.pos()

    def mouseMoveEvent(self,event):
        if event.buttons() == QtCore.Qt.LeftButton:
            self.finalPos = event.pos()
            delta = self.finalPos - self.startPos
            item_position = self.pixmap.transformOriginPoint()
            angle = math.atan2(item_position.y() - self.finalPos.y(),item_position.x() - self.finalPos.x()) / math.pi * 180 - 45
            self.parentItem().setRotation(angle)
            self.parentItem().setPos(self.parentItem().pos() + delta)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)