如何检测在PySide中绘制的椭圆上的鼠标点击?

1 投票
1 回答
1319 浏览
提问于 2025-04-18 07:32

我正在一个 QWidget 里使用 QPainter 来在黑色背景上画很多椭圆,代码如下:

paint = QPainter()
paint.begin(self)

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

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

在画完这些椭圆后,我想检测一下鼠标是否点击了其中一个椭圆。但是在 QPainter 的文档里,我没有找到明显的相关信息。

如果有其他方法可以替代 QPainter,请提供一个示例,展示如何在其他框架中实现我上面的例子。

1 个回答

1

你需要自己检测自定义区域,方法如下:

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

QGraphicsEllipseItem.contains()

另外,你也可以看看 QGraphicsEllipseItem,因为它已经实现并提供了 包含逻辑

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

然后你可以用相应的参数来创建你的对象:

scene = QGraphicsScene()
ellipseItem = MyGraphicsEllipseItem(centerx, centery, rad, rad)
scene.addItem(ellipseItem)

view = QGraphicsView(scene)
view.show()

scene.setBackgroundBrush(Qt.black)

撰写回答