【问题标题】:QGraphicsScene keep selection on empty selection marqueeQGraphicsScene 在空选择框上保持选择
【发布时间】:2015-10-01 10:20:22
【问题描述】:

我在QGraphicsScene 中有一组QGraphicsItem。我试图获得持有ctrl 键的行为并取消选择选择框内的任何项目。问题是当前选择将在鼠标按下时清除。我有什么东西可以防止这种情况发生吗?

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

【问题讨论】:

  • 似乎选择在鼠标移动过程中也会被清除,所以这可能是个问题!
  • 找到有关该问题的更多信息:asmaloney.com/2012/06/code/…

标签: python selection pyside qgraphicsview


【解决方案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 将添加到选择中,并且正常的鼠标单击将按预期清除选择。

唯一要添加的是将shiftctrl 添加到单击鼠标中,但是由于按住ctrl 确实可以添加和删除,所以现在这已经足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多