Nyaruko
Nyaruko

Reputation: 4459

How to get different context menu from qgraphicsitem inside a qgraphicsview?

I have a qgraphicsview it contains a scene and inside it there are some graphicsitem. I have enabled the context menu in qgraphicsview by setcontextmenupolicy(qt::actionscontextmenu), but now my qgraphicsitem cannot receive any qgraphicsscenecontextmenuevent event. Thus only the context menu of qgraphicsview appear.

How could I solve this?

Upvotes: 1

Views: 1905

Answers (1)

James Thompson
James Thompson

Reputation: 43

in the code below I've created my own scene class, in inheriting from QGraphicsScene

Then re-implementing the contextMenuEvent I first check if there is an item at the event position, i.e. if I'm right clicking on an item in the scene.

If so, ill instead try to run any contextMenuEvent on that item.

If there is no item, or if it doesn't have its own contextMenuEvent ill just run the scene's version of the context event.

import PySide.QtGui as QtGui import PySide.QtCore as QtCore

import PySide.QtGui as QtGui
import PySide.QtCore as QtCore

class MyScene(QtGui.QGraphicsScene):

    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)

    def contextMenuEvent(self, event):
        # Check it item exists on event position
        item = self.itemAt(event.scenePos().toPoint())
        if item:
            # Try run items context if it has one
            try:
                item.contextMenuEvent(event)
                return
            except:
                pass

        menu = QtGui.QMenu()
        action = menu.addAction('ACTION')

Upvotes: 2

Related Questions