Writing custom widgets in Gtk and python.

Many a time the default GtkWidget does not solve the job and you need a custom one with extra features. I could not find a concrete source that solves this problem. Hence here are the steps:

  1. Subclass a GtkWidget.
  2. Call the init method of the GtkWidget in the init method of your custom widget.
  3. Above all  the methods and the init method define <code> __gtype_name__ </code>. This variable will be the name of the custom widget you create and use in .ui files.
  4. Now import the widget object in the file where you define your application so that the name gets registered.
  5. Now you can use the widget in .ui files with the name you defined.

Here is an example. This also contains definition of some extra properties.

class coalaScrolledWindow(Gtk.ScrolledWindow):

    __gtype_name__ = 'coalaScrolledWindow'

    max_contentwidth = GObject.property(type=int,
                                       default=-1,
                                       flags=GObject.PARAM_READWRITE)
    max_contentheight = GObject.property(type=int,
                                        default=-1,
                                        flags=GObject.PARAM_READWRITE)

    def __init__(self, *args, **kwargs):
        Gtk.ScrolledWindow.__init__(self, *args, **kwargs)
        self.max_content_width = -1
        self.max_content_height = -1
        self.connect("notify::max-contentheight",
                     self.on_notify_max_height_changed)
        self.connect("notify::max-contentwidth",
                     self.on_notify_max_width_changed)

Registering it you just need to import it somewhere.

For further information drop a comment or go to https://www.github.com/coala-analyzer/coala and checkout the wip/udayan/gui2 branch.

Advertisements

One thought on “Writing custom widgets in Gtk and python.

  1. It’s just subclassing a GObject. Writing custom widgets is another beast, it’s when the direct parent is the GtkWidget base class and you need to implement its virtual functions, like sizing, drawing, handle input events, etc.

    What is more common is a composite widget, where you subclass e.g. GtkGrid and you pack widgets in it. See for example the gedit code architecture (there is a schema of the main classes on the wiki):
    https://wiki.gnome.org/Apps/Gedit/DevNotes

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s