[PyQt] adding context menu to graphics item

Mark Summerfield list at qtrac.plus.com
Thu Jul 8 11:28:35 BST 2010


On 2010-07-08, Christopher M. Nahler wrote:
> I need some help on how to add a context menu to a graphics item.
> 
> In the sample code below I have an action (editAction) on a menu
> (myMenu) that is only enabled if a item is selected.
> 
> Now I would like to have this menu show up as a context menu when I
> right click the rect item in the scene/view.
> 
> I think the way to do this is to do my own processing of the
> contextMenuEvent. But what is the best way to do that?
> 
> Store the menu in the scene so that I can access it from the
> graphicsItem? And then do a menu.exec in the contextMenuEvent handler?
> 
> Or are they better ways to do this? Is there some route with signalling?

Hi Chris,

Personally, I think you're doing the right thing in reimplementing the
QGraphicsRectItem::contextMenuEvent() handler. In general I would always
try to push the behaviour down to the relevant item itself. The
alternative is doing things in the scene or view but that means you have
to identify the item that is involved and adds complexity for no gain.

So I'd just create a QMenu inside the contextMenuEvent() and go from
there.

PS Since you're using Python 3.1 you can replace all your super() calls
that look like this:

          super(MyView, self).__init__(parent)

with ones that look like this:

          super().__init__(parent)

since Python 3 is a bit smarter than Python 2:-)

-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Rapid GUI Programming with Python and Qt" - ISBN 0132354187
            http://www.qtrac.eu/pyqtbook.html


More information about the PyQt mailing list