How to add a pygtk Widget to the Glade palette?

Okay, this is going to be step by step:

  • Our widget is going to be named AwesomeTextView, the module it's in will be called awesome_text_view. These are the only names we need.

A glade widget consists of two parts, the module and the catalog.

  1. We create a catalog, awesome_text_view.xml, and (as root) save it at /usr/share/glade3/catalogs/

    This is what it looks like:

    <glade-catalog name="awesome_text_view"
        library="gladepython"
        domain="glade-3"
        depends="gtk+">
    
     <init-function>glade_python_init</init-function>
    
     <glade-widget-classes>
       <glade-widget-class title="Awesome TextView"
        name="AwesomeTextView"
        generic-name="awesome_text_view"/>
     </glade-widget-classes>
    
     <glade-widget-group name="python" title="Python">
       <glade-widget-class-ref name="AwesomeTextView"/>
     </glade-widget-group>
    </glade-catalog>
    

    You should copy and adapt this template, as it works. :-)

  2. We create a module, awesome_text_view.py, and (again as root) save it at /usr/lib/glade3/modules/

    Here's what that looks like:

    import gobject
    import gtk
    import pango
    
    
    class AwesomeTextView (gtk.TextView):
    
        __gtype_name__ = 'AwesomeTextView'
    
        def __init__(self):
            gtk.TextView.__init__(self)
    
        def set_font(self, font_description):
            self.modify_font(pango.FontDescription(font_description))
    

    It's now displayed in Glade, and you can add it to your application.

  3. Finally, you'll just need to

        export PYTHONPATH="$PYTHONPATH:/usr/lib/glade3/modules/"
    

That's it!

Here's a little test app showing how to use your widget:

import gtk
import awesome_text_view

class App (object):

    builder = gtk.Builder()

    def __init__(self):
        self.builder.add_from_file("test.glade")
        self.builder.connect_signals(self)
        self.builder.get_object("awesome_text_view1").set_font("mono")
        gtk.main()

    def on_window1_destroy(self, widget):
        gtk.main_quit()


App()

You need to make a catalog for your widgets, see this folder: /usr/share/glade3/catalogs/ and you'll see gnome.xml, have a look for an example.

See also the gnome documentation:

http://developer.gnome.org/gladeui/stable/catalogintro.html