[Qgis-developer] [Python plugin] menu items: actions binding with cycle

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Wed Jul 30 07:18:00 EDT 2008


2008/7/30 Anne Ghisla <a.ghisla at studenti.uninsubria.it>:


> The code is clearly self-similar.
> I tried to write a cycle to populate the menu, but it doesn't work.
>
> [code]
> mth = {"mcp":"MCP", "href":"Kernel h ref", "lscv":"Kernel h LSCV",
> "hadj":"Kernel with adjusted h"}
> [declaration of self.action* outside cycle]
> for k, v in self.mth.iteritems():
>  a = getattr(self,  "action" + k)
>  a = QAction(QIcon(""), v , self.iface.getMainWindow())

 I'm guessing the repetition of "a=" here is a mistake?

>  a.setWhatsThis("None")
>  QObject.connect(a, SIGNAL("activated()"), lambda method=k:
> self.showInterface(method))
> [/code]
>
> I get no errors when running QGIS from a shell, but no submenu is
> displayed.

 This code won't add anything to a submenu, it only defines actions.
Are there some lines missing that call addMenu?

 Here's how spqr does this:

self.menu = QMenu("Statistics")

 then for each menu item, something like this:

self.summary = QAction(QIcon(":/graphics/summary.png"),"Summary",self.iface.getMainWindow())
QObject.connect(self.summary, SIGNAL("triggered()"), self.doSummary)
self.histogram =
QAction(QIcon(":/graphics/histogram.png"),"Histogram",self.iface.getMainWindow())
QObject.connect(self.histogram, SIGNAL("triggered()"), self.doHistogram)
[etc]

 then:

self.menu.addActions([self.summary, self.histogram, (etc)]

 to add my menu to the menu bar I do:

 menuBar = self.iface.getMainWindow().menuBar()
 menuBar.addMenu(self.menu)

 I don't think two lines of repeated code is sufficient to warrant
putting the action item description in a list.

 What could be going wrong with your code is the assignment to a local
variable 'a'. As the variable gets overwritten each time in the loop,
the underlying Qt QAction item might get cleaned up and deleted since
there are now no references to it. I've had code crash on me because
of this in the past. Note that my actions (self.summary,
self.histogram) are stored in the object.

 If you store all your actions in a list that persists in the object
(e.g. self.actions[]) then they'll persist for the life of your
application.

 Also, I'd suggest storing your action information in a python list
rather than a dict so that you can decide on the order. But I think
this approach might get fiddly once you decide to put separators in to
your menu. My spqr code explicitly adds actions and separators to the
menu in the order of the code.

 Hope that helps.

Barry


More information about the Qgis-developer mailing list