如何停止在QGraphicsScene中取消选择项目而不阻止场景中的项目的鼠标中键单击?

问题描述:

我正在创建一个节点图,我希望能够单击场景中的空白区域并鼠标中键拖动来导航而不取消选择场景中的当前选定项目。有什么建议么?如何停止在QGraphicsScene中取消选择项目而不阻止场景中的项目的鼠标中键单击?

我可以在视图的mousePressEvent中阻止中间点击并获得正确的行为,但之后我不再有在场景中的项目上工作的鼠标中点击事件。我不介意在点击场景中的一个项目时产生单击选择,但如果我中间点击场景中的空白区域,我不希望选择被改变。

这并不包括更复杂的行为我要找:PyQt. How to block clear selection on mouse right click?

我没有尝试使用eventFilter,因为我认为这个问题将是相同

我使用的PyQt/PySide ,FWIW。

在我推出我自己的解决方法之前,我想我会在这里发布正确的方法或至少其他解决方法的想法。

一些变通思路:

  • 座的mousePressEvent现场,但迭代子项直接
  • 提供它同时还在mousePressEvent在场景还原选择。我认为可能对规模效益很差,但很简单。

任何反馈将是伟大的!

[编辑:] 这是我的python版本的答案。代码测试。在我QGraphicsScene派生类:

def mousePressEvent(self, event): 
    # Prevent the QGraphicsScene default behavior to deselect-all when clicking on 
    # empty space by blocking the event in this circumstance. 
    item_under_the_mouse = self.itemAt(event.scenePos()) 
    if event.button() == QtCore.Qt.MidButton and not item_under_the_mouse: 
     event.accept() 
    else: 
     super(GraphScene, self).mousePressEvent(event) 

在你QGraphicsScene::mousePressEvent派生实现,如果它是一个中间点击鼠标,检查鼠标点击的项目。如果没有,则接受该事件并且不要调用基类实现。如果点击下面有东西,那么只需调用基本实现;你不必尝试自己重新实现。我认为这是总体思路:

void MyScene::mousePressEvent (QGraphicsSceneMouseEvent *evt) 
{ 
    if ((evt->buttons() & Qt::MidButton) && items (evt->scenePos().count()) 
    { 
     QGraphicsScene::mousePressEvent (evt); 
    } 
    else 
    { 
     evt->accept(); 
    } 
} 

我如果accept在这种情况下还是不要求不能确定。我没有编译或测试过这个,但希望能帮助你朝着正确的方向前进。

+0

这是我前进的方向。很高兴看到确认。一旦我开始工作,我会发布python版本。 – Rafe

+0

优秀...我不知道Python,但我一直觉得很容易在答案中来回转换。 – goug