2015-10-01 84 views
1

我在QGraphicsScene內收集了QGraphicsItem。我試圖獲得持有ctrl鍵的行爲,並取消選擇選取框內的任何項目。問題在於當前的選擇將在鼠標按下時清除。有什麼我錯過了,以防止這種情況?QGraphicsScene保留空選框上的選擇

我能想到的唯一的事情就是保存鼠標釋放時的當前選擇,然後在下一次鼠標按下事件時恢復它。雖然我希望避免這種情況,但這看起來不太優雅。

+0

似乎選擇也會在鼠標移動過程中清除,所以這可能是一個問題! –

+0

找到關於此問題的更多信息:http://asmaloney.com/2012/06/code/extending-selections-in-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將添加到選擇和正常鼠標點擊只會清除選擇預期。

添加到這一點的唯一的事情是將包括shift & ctrl到一個單一的鼠標點擊,但由於控股ctrl並添加和刪除,那麼這是不夠好現在。