| FAQ Index - Search - Recent Changes - Everything - Add entry |
22.7. How do I create and use a custom Glade widget?
Ross Burton wrote a patch for custom widget support, which has been integrated into PyGTK-2. A working example follows.
import gtk
import gtk.glade
def create_source_cd_dropdown():
return gtk.Label("source")
gtk.glade.set_custom_widget_callbacks(locals())
glade = gtk.glade.XML("cd-copier.glade")
window = glade.get_widget("window")
window.show_all()
gtk.main()
Note that the glade file must define the proper callback name for the custom widget; in this case, create_source_cd_dropdown. The important call is gtk.glade.set_custom_widget_callbacks(), which takes a dictionary of function names->functions (which is why locals() works in the example).
The above method is deprecated in recent versions of pygtk.
The new API uses the method gtk.glade.set_custom_handler, which allows you to treat widget creation more dynamically if you wish.The set_custom_handler API works as follows:
def my_handler (glade, function_name, widget_name, str1, str2, int1 , int2):
# create your widget based on our arguments...
return a_custom_widget
gtk.glade.set_custom_handler(my_handler)
The following example, adapted from SimpleGladeApp.py in Sandino Flores Moreno's SimpleGladeApp.py shows how to use set_custom_handler to allow you to create custom handler constructors simply by naming class methods with the constructor names.
IMPORTANT: The call to gtk.glade.set_custom_handler() (as well gtk.glade.set_custom_widget_callbacks()) must come before the load of any Glade widget (by calling gtk.glade.XML()). The reason is that Glade needs to call the handlers when processing the XML file. The handlers are used to construct widgets, which happens at construction-time.
class MyGladeApp:
def __init__ (self):
gtk.glade.set_custom_handler(self.get_custom_handler)
self.glade = gtk.glade.XML('/path/to/gladefile.glade')
...
def get_custom_handler(self, glade, function_name, widget_name,
str1, str2, int1, int2):
"""
Generic handler for creating custom widgets, used to
enable custom widgets.
The custom widgets have a creation function specified in design time.
Those creation functions are always called with str1,str2,int1,int2 as
arguments, that are values specified in design time.
This handler assumes that we have a method for every custom widget
creation function specified in glade.
If a custom widget has create_foo as creation function, then the
method named create_foo is called with str1,str2,int1,int2 as arguments.
"""
handler = getattr(self, function_name)
return handler(str1, str2, int1, int2)
