Subclassing#

Before entering in detail, you should know some important points about GObject subclassing:

  1. It is possible to subclass a GObject.Object. Subclassing creates a new GObject.GType which is connected to the new Python type. This means you can use it with API which takes GObject.GType.

  2. GObject.Object only supports single inheritance, this means you can only subclass one GObject.Object, but multiple Python classes.

  3. The Python wrapper instance for a GObject.Object is always the same. For the same C instance you will always get the same Python instance.

Inherit from GObject.GObject#

A native GObject is accessible via GObject.Object. It is rarely instantiated directly, we generally use an inherited classes. A Gtk.Widget is an inherited class of a GObject.Object. It may be interesting to make an inherited class to create a new widget, like a settings dialog.

To inherit from GObject.Object, you must call super().__init__() in your constructor to initialize the gobjects you are inheriting, like in the example below:

from gi.repository import GObject

class MyObject(GObject.Object):

    def __init__(self):
        super().__init__(self)

You can also pass arguments to super().__init__(), for example to change some property of your parent gobject:

class MyWindow(Gtk.Window):

    def __init__(self):
        super().__init__(self, title='Custom title')

In case you want to specify the GType name we have to provide a __gtype_name__:

class MyWindow(Gtk.Window):
    __gtype_name__ = 'MyWindow'

    def __init__(self):
        super().__init__(self)

Properties#

One of the nice features of GObject is its generic get/set mechanism for object properties. Any class that inherits from GObject.Object can define new properties. Each property has a type that never changes (e.g. str, float, int…).

Create new properties#

A property is defined with a name and a type. Even if Python itself is dynamically typed, you can’t change the type of a property once it is defined. A property can be created using GObject.Property().

from gi.repository import GObject

class MyObject(GObject.Object):

    foo = GObject.Property(type=str, default='bar')
    property_float = GObject.Property(type=float)

    def __init__(self):
        super().__init__(self)

Properties can also be read-only, if you want some properties to be readable but not writable. To do so, you can add some flags to the property definition, to control read/write access. Flags are GObject.ParamFlags.READABLE (only read access for external code), GObject.ParamFlags.WRITABLE (only write access), GObject.ParamFlags.READWRITE (public):

foo = GObject.Property(type=str, flags=GObject.ParamFlags.READABLE) # not writable
bar = GObject.Property(type=str, flags=GObject.ParamFlags.WRITABLE) # not readable

You can also define new read-only properties with a new method decorated with GObject.Property():

from gi.repository import GObject

class MyObject(GObject.Object):

    def __init__(self):
        super().__init__(self)

    @GObject.Property
    def readonly(self):
        return 'This is read-only.'

You can get this property using:

my_object = MyObject()
print(my_object.readonly)
print(my_object.get_property('readonly'))

The API of GObject.Property() is similar to the builtin property. You can create property setters in a way similar to Python property:

class AnotherObject(GObject.Object):
    value = 0

    @GObject.Property
    def prop(self):
        'Read only property.'
        return 1

    @GObject.Property(type=int)
    def prop_int(self):
        'Read-write integer property.'
        return self.value

    @prop_int.setter
    def prop_int(self, value):
        self.value = value

There is also a way to define minimum and maximum values for numbers, using a more verbose form:

from gi.repository import GObject

class MyObject(GObject.Object):

    __gproperties__ = {
        'int-prop': (
            int, # type
            'integer prop', # nick
            'A property that contains an integer', # blurb
            1, # min
            5, # max
            2, # default
            GObject.ParamFlags.READWRITE # flags
        ),
    }

    def __init__(self):
        super().__init__(self)
        self.int_prop = 2

    def do_get_property(self, prop):
        if prop.name == 'int-prop':
            return self.int_prop
        else:
            raise AttributeError('unknown property %s' % prop.name)

    def do_set_property(self, prop, value):
        if prop.name == 'int-prop':
            self.int_prop = value
        else:
            raise AttributeError('unknown property %s' % prop.name)

For this approach properties must be defined in the __gproperties__ class attribute, a dictionary, and handled in GObject.Object.do_get_property() and GObject.Object.do_set_property() virtual methods.

Signals#

Each signal is registered in the type system together with the type on which it can be emitted: users of the type are said to connect to the signal on a given type instance when they register a function to be invoked upon the signal emission. Users can also emit the signal by themselves or stop the emission of the signal from within one of the functions connected to the signal.

Create new signals#

New signals can be created by adding them to the __gsignals__ class attribute, a dictionary:

When a new signal is created, a method handler can also be defined, it will be called each time the signal is emitted. It is called do_signal_name.

class MyObject(GObject.Object):
    __gsignals__ = {
        'my_signal': (
            GObject.SIGNAL_RUN_FIRST,
            None,
            (int,)
        )
    }

    def do_my_signal(self, arg):
        print("method handler for `my_signal' called with argument", arg)

GObject.SIGNAL_RUN_FIRST indicates that this signal will invoke the object method handler (do_my_signal() here) in the first emission stage. Alternatives are GObject.SIGNAL_RUN_LAST (the method handler will be invoked in the third emission stage) and GObject.SIGNAL_RUN_CLEANUP (invoke the method handler in the last emission stage).

The second part, None, indicates the return type of the signal, usually None.

(int,) indicates the signal arguments, here, the signal will only take one argument, whose type is int. Types of arguments required by signal are declared as a sequence, here it is a one-element tuple.

Signals can be emitted using GObject.Object.emit():

my_obj.emit('my_signal', 42) # emit the signal "my_signal", with the
                             # argument 42

Virtual Methods#

GObject and its based libraries usually have gobjects that expose virtual methods. These methods serve to override functionality of the base gobject or to run code on a specific scenario. In that case you should call the base gobject virtual method to preserve its original behavior.

In PyGObject these methods are prefixed with do_. Some examples are GObject.Object.do_get_property() or Gio.Application.do_activate().

Important

The Python super class only works for the immediate parent. If you want to chain some virtual method from a object that is more up in the hierarchy of the one you are subclassing you must call the method directly from the object class: SomeOject.method(self, args).

class MyObject(OtherObject):

    def __init__(self):
        super().__init__(self)

    def do_virtual_method(self):
        # Call the original method to keep its original behavior
        super().do_virtual_method(self)

        # Run some extra code
        ...

    ''' This is a virtual method from some OtherObject parent '''
    def do_other(self):
        SomeOject.do_other(self)
        ...