subclassing wxMenuBar...

Tom Jenkins tjenkins at devis.com
Mon Jun 4 09:26:28 EDT 2001


Bjorn Pettersen wrote:

> I was stepping through the wxPython tutorial, and came across the part
> where they're creating the menus. It seemed like a good idea to put the
> menu definition in a datafile instead of specifying it programatically,
> so I though it would be a good chance to get some xml experience too...
> 


Yep, that makes sense...

[snip]


> which I'm assuming means that the SWIGd code is expecting a wxMenuBar
> pointer to be the first argument to Append and can't deal with a
> subclass...
> 
> Does anyone know a way around this?
> 
> -- bjorn
> 
> 

Well I wouldn't subclass wxMenuBar; instead I'd create a helper class 
that would handle reading the xml and loading it into the wxMenuBar.  I 
took your code and changed it to work as a helper.  Along the way I 
added some functionality.

First I changed the format of the xml by wrapping it in a menubar tag. 
<menubar>
<menu name="_Test">
	<menuitem id="101" name="_About"... />
	<menuitem id="103" name="_Change" info="Change title?"/>
	<separator/>
	<menuitem id="102" name="E_xit".../>
</menu>
<menu name="_Edit">
	<menuitem id="201" name="Copy" info="Copy" callback='onCopy'/>
	<menuitem id="202" name="Cut" info="Cut" callback='onCut'/>
</menu>
</menubar>

This allows us to have one or more menu elements. To handle this in the 
code, I changed the for loop to loop over each "menu" element in the 
menubar:
   menubar = minidom.parse(self._filename)
   # loop over and process all of the menu elements in the menubar
   for menu in menubar.getElementsByTagName('menu'):

Another addition I made was to add a callback attribute.  Then if you 
pass a class instance to the load method, the load method will attempt 
to hookup the method name set in the callback attribute in the 
controller class instance.

To use this new class you would do the following in the frame:
   loader = XMLMenuLoader('menu.xml')
   loader.load(wxMenuBar = self.mainmenu, controller=self)
   loader.setMenuBar(None)

By changing your original code from a subclass of a wxMenuBar to an 
helper class, we can expand the usefulness.  Perhaps instead of xml we 
decide to use nested lists?  We can refactor the XMLMenuLoader class 
into a base MenuLoader class and various subclasses.

Thanks for the initial post Bjorn, I had fun working on this...

-- 
Tom Jenkins
devIS - Development Infostructure
http://www.devis.com
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: menu.py
URL: <http://mail.python.org/pipermail/python-list/attachments/20010604/ce458c75/attachment.ksh>


More information about the Python-list mailing list