PyQt: Mouse events in QGraphicsView

只谈情不闲聊 提交于 2019-12-06 04:13:07

In a QGraphicsView a QGraphicsScene is added, each one manages a system of different coordinates. the QGraphicsView is similar to a camera and a QGraphicsScene is similar to the world, when one adds an item to the scene it must be in its coordinate system.

As you want to add items when you click, it is better to overwrite the mousePressEvent method of QGraphicsScene, and get the position in the coordinates of the scene for which the scenePos() method is used.

Another thing to do is to initialize the attribute setSceneRect() which is the space that QGraphicsView can see.

A recommendation if several buttons are used use a QButtonGroup that maps the buttons making easy the easy handling of the signals.

class GraphicsScene(QGraphicsScene):
    def __init__(self, parent=None):
        QGraphicsScene.__init__(self, parent)
        self.setSceneRect(-100, -100, 200, 200)
        self.opt = ""

    def setOption(self, opt):
        self.opt = opt

    def mousePressEvent(self, event):
        pen = QPen(QtCore.Qt.black)
        brush = QBrush(QtCore.Qt.black)
        x = event.scenePos().x()
        y = event.scenePos().y()
        if self.opt == "Generate":
            self.addEllipse(x, y, 4, 4, pen, brush)
        elif self.opt == "Select":
            print(x, y)


class SimpleWindow(QtWidgets.QMainWindow, points.Ui_Dialog):
    def __init__(self, parent=None):
        super(SimpleWindow, self).__init__(parent)
        self.setupUi(self)

        self.scene = GraphicsScene(self)
        self.graphicsView.setScene(self.scene)
        self.graphicsView.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)

        group = QButtonGroup(self)
        group.addButton(self.radioButton)
        group.addButton(self.radioButton_2)

        group.buttonClicked.connect(lambda btn: self.scene.setOption(btn.text()))
        self.radioButton.setChecked(True)
        self.scene.setOption(self.radioButton.text())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!