PyQt:图形场景椭圆的悬停和单击事件 [英] PyQt: hover and click events for graphicscene ellipse
问题描述
我想知道用户是否将鼠标悬停在或单击 GraphicsScene 形状对象(例如,我在下面评论的椭圆对象).我是 PyQt 的新手,C++ 的文档比 Python 好得多,所以我在弄清楚这个问题时遇到了一些麻烦.
I'd like to find out if a user hovers over or clicks a GraphicsScene shape object (for example, the ellipse object I commented below). I'm new to PyQt and the documentation is much better for C++ than Python, so I'm having a bit of trouble figuring this one out.
from PyQt4 import QtGui, QtCore
class MyFrame(QtGui.QGraphicsView):
def __init__( self, parent = None ):
super(MyFrame, self).__init__(parent)
self.setScene(QtGui.QGraphicsScene())
# add some items
x = 0
y = 0
w = 45
h = 45
pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.green))
brush = QtGui.QBrush(pen.color().darker(150))
# i want a mouse over and mouse click event for this ellipse
item = self.scene().addEllipse(x, y, w, h, pen, brush)
item.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
if ( __name__ == '__main__' ):
app = QtGui.QApplication([])
f = MyFrame()
f.show()
app.exec_()
更新!!!
现在我可以根据释放鼠标单击来触发事件.不幸的是,只有我创建的最后一个项目可以响应事件.这是怎么回事?
Now I can get an event to take place based on a mouse click release. Unfortunately, only the last item I create can respond to events. What's going on here?
from PyQt4 import QtGui, QtCore
class MyFrame(QtGui.QGraphicsView):
def __init__( self, parent = None ):
super(MyFrame, self).__init__(parent)
self.setScene(QtGui.QGraphicsScene())
# add some items
x = 0
y = 0
w = 20
h = 20
pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.green))
brush = QtGui.QBrush(pen.color().darker(150))
# i want a mouse over and mouse click event for this ellipse
for xi in range(10):
for yi in range(10):
item = callbackRect(x+xi*30, y+yi*30, w, h)
item.setAcceptHoverEvents(True)
item.setPen(pen)
item.setBrush(brush)
self.scene().addItem(item)
# item = self.scene().addEllipse(x, y, w, h, pen, brush)
item.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
class callbackRect(QtGui.QGraphicsRectItem):
'''
Rectangle call-back class.
'''
def mouseReleaseEvent(self, event):
# recolor on click
color = QtGui.QColor(180, 174, 185)
brush = QtGui.QBrush(color)
QtGui.QGraphicsRectItem.setBrush(self, brush)
return QtGui.QGraphicsRectItem.mouseReleaseEvent(self, event)
def hoverMoveEvent(self, event):
# Do your stuff here.
pass
if ( __name__ == '__main__' ):
app = QtGui.QApplication([])
f = MyFrame()
f.show()
app.exec_()
推荐答案
您可以定义自己的椭圆类并替换单击和悬停事件:
You can define your own ellipse class and replace both click and hover events:
class MyEllipse(QtGui.QGraphicsEllipseItem):
def mouseReleaseEvent(self, event):
# Do your stuff here.
return QtGui.QGraphicsEllipseItem.mouseReleaseEvent(self, event)
def hoverMoveEvent(self, event):
# Do your stuff here.
pass
用法:
item = MyEllipse(x, y, w, h)
item.setAcceptHoverEvents(True)
item.setPen(pen)
item.setBrush(brush)
self.scene().addItem(item)
希望有帮助!
这篇关于PyQt:图形场景椭圆的悬停和单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!