【问题标题】:How to stop a middle mouse click from deselecting items in a QGraphicsScene without blocking it from items in the scene?如何阻止鼠标中键单击取消选择 QGraphicsScene 中的项目而不阻止它与场景中的项目相结合?
【发布时间】:2017-03-06 22:00:12
【问题描述】:

我正在创建一个节点图,我希望能够单击场景中的空白区域并通过鼠标中键拖动进行导航,而无需取消选择场景中当前选定的项目。有什么建议吗?

我可以阻止视图的 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)

【问题讨论】:

    标签: qt pyqt selection qgraphicsscene qgraphicsitem


    【解决方案1】:

    在您的QGraphicsScene::mousePressEvent 派生实现中,如果是鼠标中键单击,请检查鼠标单击下的项目。如果没有,则接受该事件并且不要调用基类实现。如果点击了某些东西,那么只需调用基本实现;您不必尝试自己重新实现它。我认为这是一般的想法:

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

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

    【讨论】:

    • 这是我前进的方向。很高兴看到确认。一旦我得到它的工作,我会发布 python 版本。
    • 优秀...我不懂 Python,但我发现在答案中来回转换很容易。
    猜你喜欢
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2021-08-30
    • 2015-01-08
    相关资源
    最近更新 更多