问题
I have a QGraphicsScene and many selectable items. But when I click the right mouse button - deselects all objects. I want show menu and edit selected objects but have automatic deselect any time when right click at mouse...
Perhaps the problem is that I have included an rubber selection. selection of objects in the end is how the right and the left mouse button when I pull the frame and therefore is reset at single time you press the right button...
How to leave objects highlighted when you click on the right mouse button? Or it may be necessary to disable the rubber selection of the right button?
回答1:
Daniele Pantaleone answer gave me an idea and I have modified the function of mousePressEvent()
and immediately got the desired effect me
def mousePressEvent(self, event):
if event.button() == Qt.MidButton:
self.__prevMousePos = event.pos()
elif event.button() == Qt.RightButton: # <--- add this
print('right')
else:
super(MyView, self).mousePressEvent(event)
回答2:
A possible solution would be to use mouseReleaseEvent
to display the contextual menu instead of contextMenuEvent
:
def mouseReleaseEvent(self, mouseEvent):
if mouseEvent.button() == Qt.RightButton:
# here you do not call super hence the selection won't be cleared
menu = QMenu()
menu.exec_(mouseEvent.screenPos())
else:
super().mouseReleaseEvent(mouseEvent)
I haven't been able to test it but I guess it should work. The point is that the selection is cleared by default by QGraphicsScene
, so what you need to do is to prevent the clearing from happening when certain conditions are met, in your case when the contextual menu needs to be displayed.
来源:https://stackoverflow.com/questions/36035663/pyqt-how-to-block-clear-selection-on-mouse-right-click