QGraphicsScene在空选择选框上保持选择

时间:2015-10-01 10:20:22

标签: python selection pyside qgraphicsview

我在ctrl内有一个#!/usr/bin/octave -q a = input(""); b = input(""); printf("%d", a+b); 的集合。我试图获取持有{{1}}键的行为并取消选择选择框内的任何项目。问题是当前选择将在鼠标按下时清除。我有什么东西可以防止这种情况发生吗?

我唯一能想到的是在鼠标释放时保存当前选择,然后在下一次鼠标按下事件中恢复它。这似乎并不优雅,但我希望避免这种情况。

1 个答案:

答案 0 :(得分:1)

这给了我正在寻找的行为。我知道这不是最有效的方法,所以如果仍然可以改进,请告诉我!

# 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会添加AND删除,所以现在这已足够了。