Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt: Basic example of accessing and adding a submenu to an existing context menu?

Note: I have very little python and PyQt experience...

Given a context menu already created, I'm looking for a functional example of how I would gain access to that context menu, so it can be extended for a plugin which is doing the python equivalent of a javascript greasemonkey script. Then I'm also looking for a functional example of how I could add a submenu to that context menu. Thanks!

like image 468
BrianFreud Avatar asked Jan 20 '26 23:01

BrianFreud


2 Answers

The customContextMenuRequested signal would be connected to a method/function (called a slot in Qt), look for a line of code that resembles this to get an idea of what method/function you need to adjust:

self.centralwidget.customContextMenuRequested.connect(self.context_menu_method)

so for that example you would need to adjust self.context_menu_method, that is what is actually creating the menu

and for a code example of how to add a submenu:

menu = QtGui.QMenu()
submenu = QtGui.QMenu(menu)
submenu.setTitle("Submenu")
menu.addMenu(submenu)
like image 83
Karnisov Avatar answered Jan 22 '26 17:01

Karnisov


Avaris' comments basically answered this question the best. I can't select it, though, because it's comments, rather than an answer. So I'm summarizing that answer here, so this Q can be answered:

"If you are given a context menu (QMenu to be specific) you can access it." - Avaris

"You can't do this without modifying that file [the one containing the context menu creation code]. It assumes it has given a list of QActions (see line 301) and it wouldn't be expecting QMenu. Though, if you can get to the plugin_menu reference in your plugin, that's a different story." - Avaris

So either you can access to manipulate the menu in the same file (and same place in that file) where the menu creation/definition code is, or you can gain access to do so via that file (in the same place) exposing the menu via an API. On the flip side, if you don't have such API access, and/or modify that file/function, then there's no way to do this.

like image 43
BrianFreud Avatar answered Jan 22 '26 17:01

BrianFreud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!