1

QGraphicsPixmapItem画像の左上隅にある円を移動する必要があります。つまり、マウスで円をつかむとき、画像の左上隅が円をたどる必要があります。a をサブクラス化しQGraphicsEllipseItem、メソッドを再実装しましたitemChangeが、画像の位置をその値に設定すると、画像が正しく配置されません。コードで何を変更する必要がありますか?

    import sys
    from PyQt5.QtWidgets import QMainWindow, QApplication, QGraphicsView
    from PyQt5 import QtGui, QtWidgets
    
    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.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)
    
        def set_pixmap(self):
            pixmap = QtGui.QPixmap("image.jpg")
            self.setPixmap(pixmap)
            self.pixmap_controller = PixmapController(self)
            self.pixmap_controller.set_pixmap_controller()
            self.pixmap_controller.setPos(self.boundingRect().topLeft())
            self.pixmap_controller.setFlag(QtWidgets.QGraphicsItem.ItemSendsScenePositionChanges, True)
    
        def change_image_position(self, position):
            self.setPos(position)
    
    class PixmapController(QtWidgets.QGraphicsEllipseItem):
        def __init__(self, pixmap):
            super(PixmapController, self).__init__(parent=pixmap)
            self.pixmap = pixmap
    
            self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
            color = QtGui.QColor(0, 0, 0)
            brush = QtGui.QBrush(color)
            self.setBrush(brush)
    
        def set_pixmap_controller(self):
            self.setRect(-5, -5, 10, 10)
    
        def itemChange(self, change, value):
            if change == QtWidgets.QGraphicsItem.ItemPositionChange:
                self.pixmap.change_image_position(value)
            return super(PixmapController, self).itemChange(change, value)
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        window = MainWindow()
        window.show()
        sys.exit(app.exec_())
4

1 に答える 1