我在QGraphicsScene
内有一个QGraphicsItem
集合。我试图获得按住 ctrl 键并取消选择选择选取框内的任何项目的行为。问题是按下鼠标时当前选择将被清除。我是否缺少某些东西来防止这种情况发生?
我唯一能想到的是在鼠标释放时保存当前选择,然后在下一个鼠标按下事件时恢复它。但这看起来不太优雅,所以我希望避免这种情况。
最佳答案
这给了我我正在寻找的行为。我知道这不是最有效的方法,所以请让我知道这是否仍然可以改进!
# Override double click event so it doesn't clear selection
def mouseDoubleClickEvent(self, event):
pass
def mousePressEvent(self, event):
QtGui.QGraphicsView.mousePressEvent(self, event)
# Save state of mouse button and any key modifiers
self.mouseButton = event.button()
self.modifiers = event.modifiers()
# If a modifier key is held, don't clear the selection!
if self.modifiers == QtCore.Qt.SHIFT or self.modifiers == QtCore.Qt.CTRL:
if self.lastSelection:
for item in self.lastSelection:
item.setSelected(True)
else:
self.scene().clearSelection()
def mouseMoveEvent(self, event):
QtGui.QGraphicsView.mouseMoveEvent(self, event)
# Only apply if the left mouse button is being held down
if self.mouseButton == QtCore.Qt.MouseButton.LeftButton:
# Add items to current selection if shift is held down
if self.modifiers == QtCore.Qt.SHIFT:
sel = set( self.lastSelection ).union( set( self.scene().selectedItems() ) )
for item in sel:
item.setSelected(True)
# Remove items from current selection if ctrl is held down
elif self.modifiers == QtCore.Qt.CTRL:
sel = set( self.lastSelection ).union( set( self.scene().selectedItems() ) )
dif = set( self.lastSelection ).symmetric_difference( set( self.scene().selectedItems() ) )
for item in sel:
selectState = not (item not in self.lastSelection or item not in dif)
item.setSelected(selectState)
def mouseReleaseEvent(self, event):
QtGui.QGraphicsView.mouseReleaseEvent(self, event)
# Reset values
self.mouseButton = None
self.modifiers = None
self.lastSelection = self.scene().selectedItems() # Store last selected items
现在,如果我按住ctrl
,它将取消选择项目,按住shift
将添加到选择中,而普通的鼠标单击将按预期清除选择。
唯一要添加的就是将 shift
和 ctrl
包含到单次鼠标单击中,但由于按住 ctrl
确实会添加并删除,那么现在就足够了。
关于python - QGraphicsScene 将选择保留在空选择框上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32885094/