views:

54

answers:

1

I do not understand why in the book Rapid GUI Programming with Python and Qt, a context menu is added to a central widget by calling addActions() on the main window (self), like so (p. 180):

self.addActions(self.imageLabel,
                (editInvertAction, …))

where self is a QMainWindow, and imageLabel is a QLabel set as the central widget with

self.imageLabel.setContextMenuPolicy(Qt.ActionsContextMenu)  # Added actions will be put in a context menu
self.setCentralWidget(self.imageLabel)

Now, why would the main window be associated in some way (through self.addActions()) to the context menu of the central widget? Isn't it enough to call addActions() directly on the central widget? In fact, the following does create a context menu:

self.imageLabel.addActions((editInvertAction, …))

Why doesn't the book example the context menu this way? isn't this equivalent to the more involved self.addActions(…) form?

PS: I even see that the documentation for QMainWindow.addActions() does not even mention any first argument (self.imageLabel, above)! I'm completely lost as to why the book uses the first snippet above instead of the last one… Help! :)

+1  A: 

Using self.addAction() on QMainWindow allow all QMainWindow childs (Docks, StatusBar, ToolBar, MenuBar, ...) to use theses actions, not only the central widget.

But the best way to get a fine-grained context menu control is to use the customContextMenuRequested signal (http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qwidget.html#customContextMenuRequested).

iksaif
Thank you! The actions passed to the central widget are already used by children of the QMainWindow (menu, etc.), and I don't see the context menu anywhere outside of the central widget. So, I'm not sure to understand your response… :)
EOL
Hum, sorry, I didn't see the "self.imageLabel," inside the first self.addActions. Maybe the book is just wrong.(Something like QWidget.addAction(self.imageLabel, (editInvertAction, …)) would probably work, but it's ugly).Use self.imageLabel.addActions or, better, the customContextMenuRequested signal.
iksaif
The book's code seems to be doing what is intended, though. Thank you for your useful input!
EOL