Search code examples
pythonqtpysideqwidgetqgraphicsview

How to detect mouse click on ellipse drawn in pyside?


I am using QPainter within a QWidget to draw a bunch of ellipses on a black background as follows:

paint = QPainter()
paint.begin(self)

paint.setBrush(Qt.black)
paint.drawRect(event.rect())

brush = ...
paint.setBrush(brush)
paint.drawEllipse(center, rad, rad)

After a bunch of ellipses were drawn, and then I want to detect a mouse click on one of such an existing ellipse. I did not find any obvious in the documentation for QPainter.

In case there is something else to be used instead of QPainter, please provide an example that shows my above example in the other framework.


Solution

  • You will need to detect the custom area yourself as follows:

    def mousePressEvent(self, event):
        ''' You will have to implement the contain algorithm yourself'''
        if sel.fo(even.pos()):
            self.myMethod()
    

    QGraphicsEllipseItem.contains()

    Alternatively, you could look into the QGraphicsEllipseItem because it has the contains-logic implemented and offered.

    def mousePressEvent(self, event):
        if self.contains(event.pos()):
            self.myMethod()
    

    and you create your object with the corresponding parameters:

    scene = QGraphicsScene()
    ellipseItem = MyGraphicsEllipseItem(centerx, centery, rad, rad)
    scene.addItem(ellipseItem)
    
    view = QGraphicsView(scene)
    view.show()
    
    scene.setBackgroundBrush(Qt.black)