PyQt。如何阻止鼠标右键单击清除选择?

PyQt. How to block clear selection on mouse right click?

我有一个 QGraphicsScene 和许多可选项目。但是当我单击鼠标右键时 - 取消选择所有对象。我想显示菜单和编辑选定的对象,但在鼠标右键单击时随时自动取消选择...

也许问题是我选择了橡胶。对象的选择到底是怎样的,当我拉框的时候鼠标左右键是怎么复位的,所以按一下右键就复位了...

如何在单击鼠标右键时使对象高亮显示?或者可能需要禁用右键的橡胶选择?

一个可能的解决方案是使用 mouseReleaseEvent 来显示上下文菜单而不是 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)

我无法测试它,但我想它应该可以工作。关键是默认情况下选择被QGraphicsScene清除,所以你需要做的是防止在满足某些条件时发生清除,在你的情况下需要显示上下文菜单时。

Daniele Pantaleone 的回答给了我一个想法,我修改了 mousePressEvent() 的功能并立即得到了我想要的效果

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)