| 1 |
.. currentmodule:: gi.repository |
| 2 |
|
| 3 |
Subclassing |
| 4 |
=========== |
| 5 |
|
| 6 |
Before entering in detail, you should know some important points about GObject |
| 7 |
subclassing: |
| 8 |
|
| 9 |
1. It is possible to subclass a :class:`GObject.Object`. Subclassing creates a |
| 10 |
new :class:`GObject.GType` which is connected to the new Python type. |
| 11 |
This means you can use it with API which takes :class:`GObject.GType`. |
| 12 |
|
| 13 |
2. :class:`GObject.Object` only supports single inheritance, this means you can |
| 14 |
only subclass one :class:`GObject.Object`, but multiple Python classes. |
| 15 |
|
| 16 |
3. The Python wrapper instance for a GObject.Object is always the same. For the |
| 17 |
same C instance you will always get the same Python instance. |
| 18 |
|
| 19 |
|
| 20 |
Inherit from GObject.GObject |
| 21 |
---------------------------- |
| 22 |
A native GObject is accessible via :class:`GObject.Object`. |
| 23 |
It is rarely instantiated directly, we generally use an inherited classes. |
| 24 |
A :class:`Gtk.Widget` is an inherited class of a :class:`GObject.Object`. |
| 25 |
It may be interesting to make an inherited class to create a new widget, like a |
| 26 |
settings dialog. |
| 27 |
|
| 28 |
To inherit from :class:`GObject.Object`, you must call `super().__init__` |
| 29 |
in your constructor to initialize the gobjects you are inheriting, like in the |
| 30 |
example below: |
| 31 |
|
| 32 |
.. code:: python |
| 33 |
|
| 34 |
from gi.repository import GObject |
| 35 |
|
| 36 |
class MyObject(GObject.Object): |
| 37 |
|
| 38 |
def __init__(self): |
| 39 |
super().__init__() |
| 40 |
|
| 41 |
You can also pass arguments to `super().__init__`, for example to change |
| 42 |
some property of your parent gobject: |
| 43 |
|
| 44 |
.. code:: python |
| 45 |
|
| 46 |
class MyWindow(Gtk.Window): |
| 47 |
|
| 48 |
def __init__(self): |
| 49 |
super().__init__(title='Custom title') |
| 50 |
|
| 51 |
|
| 52 |
In case you want to specify the GType name we have to provide a |
| 53 |
``__gtype_name__``: |
| 54 |
|
| 55 |
.. code:: python |
| 56 |
|
| 57 |
class MyWindow(Gtk.Window): |
| 58 |
__gtype_name__ = 'MyWindow' |
| 59 |
|
| 60 |
def __init__(self): |
| 61 |
super().__init__() |
| 62 |
|
| 63 |
|
| 64 |
Properties |
| 65 |
---------- |
| 66 |
One of the nice features of GObject is its generic get/set mechanism for object |
| 67 |
properties. |
| 68 |
Any class that inherits from GObject.Object can define new properties. |
| 69 |
Each property has a type that never changes (e.g. ``str``, ``float``, |
| 70 |
``int``...). |
| 71 |
|
| 72 |
Create new properties |
| 73 |
^^^^^^^^^^^^^^^^^^^^^ |
| 74 |
|
| 75 |
A property is defined with a name and a type. Even if Python itself is |
| 76 |
dynamically typed, you can't change the type of a property once it is defined. A |
| 77 |
property can be created using :func:`GObject.Property`. |
| 78 |
|
| 79 |
.. code:: python |
| 80 |
|
| 81 |
from gi.repository import GObject |
| 82 |
|
| 83 |
class MyObject(GObject.Object): |
| 84 |
|
| 85 |
foo = GObject.Property(type=str, default='bar') |
| 86 |
property_float = GObject.Property(type=float) |
| 87 |
|
| 88 |
def __init__(self): |
| 89 |
super().__init__() |
| 90 |
|
| 91 |
Properties can also be read-only, if you want some properties to be readable but |
| 92 |
not writable. To do so, you can add some flags to the property definition, to |
| 93 |
control read/write access. |
| 94 |
Flags are :attr:`GObject.ParamFlags.READABLE` (only read access for external |
| 95 |
code), |
| 96 |
:attr:`GObject.ParamFlags.WRITABLE` (only write access), |
| 97 |
:attr:`GObject.ParamFlags.READWRITE` (public): |
| 98 |
|
| 99 |
.. there is also construct things, but they |
| 100 |
.. doesn't seem to be functional in Python |
| 101 |
|
| 102 |
.. code:: python |
| 103 |
|
| 104 |
foo = GObject.Property(type=str, flags=GObject.ParamFlags.READABLE) # not writable |
| 105 |
bar = GObject.Property(type=str, flags=GObject.ParamFlags.WRITABLE) # not readable |
| 106 |
|
| 107 |
|
| 108 |
You can also define new read-only properties with a new method decorated with |
| 109 |
:func:`GObject.Property`: |
| 110 |
|
| 111 |
.. code:: python |
| 112 |
|
| 113 |
from gi.repository import GObject |
| 114 |
|
| 115 |
class MyObject(GObject.Object): |
| 116 |
|
| 117 |
def __init__(self): |
| 118 |
super().__init__() |
| 119 |
|
| 120 |
@GObject.Property |
| 121 |
def readonly(self): |
| 122 |
return 'This is read-only.' |
| 123 |
|
| 124 |
You can get this property using: |
| 125 |
|
| 126 |
.. code-block:: python |
| 127 |
|
| 128 |
my_object = MyObject() |
| 129 |
print(my_object.readonly) |
| 130 |
print(my_object.get_property('readonly')) |
| 131 |
|
| 132 |
The API of :func:`GObject.Property` is similar to the builtin |
| 133 |
:py:class:`property`. |
| 134 |
You can create property setters in a way similar to Python property: |
| 135 |
|
| 136 |
.. code-block:: python |
| 137 |
|
| 138 |
class AnotherObject(GObject.Object): |
| 139 |
value = 0 |
| 140 |
|
| 141 |
@GObject.Property |
| 142 |
def prop(self): |
| 143 |
"""Read only property.""" |
| 144 |
return 1 |
| 145 |
|
| 146 |
@GObject.Property(type=int) |
| 147 |
def prop_int(self): |
| 148 |
"""Read-write integer property.""" |
| 149 |
return self.value |
| 150 |
|
| 151 |
@prop_int.setter |
| 152 |
def prop_int(self, value): |
| 153 |
self.value = value |
| 154 |
|
| 155 |
There is also a way to define minimum and maximum values for numbers: |
| 156 |
|
| 157 |
.. code-block:: python |
| 158 |
|
| 159 |
class AnotherObject(GObject.Object): |
| 160 |
value = 0 |
| 161 |
|
| 162 |
@GObject.Property(type=int, minimum=0, maximum=100) |
| 163 |
def prop_int(self): |
| 164 |
"""Integer property with min-max.'""" |
| 165 |
return self.value |
| 166 |
|
| 167 |
@prop_int.setter |
| 168 |
def prop_int(self, value): |
| 169 |
self.value = value |
| 170 |
|
| 171 |
|
| 172 |
my_object = AnotherObject() |
| 173 |
my_object.prop_int = 200 # This will fail |
| 174 |
|
| 175 |
Alternatively you can use the more verbose `__gproperties__` class |
| 176 |
attribute to define properties: |
| 177 |
|
| 178 |
.. code:: python |
| 179 |
|
| 180 |
from gi.repository import GObject |
| 181 |
|
| 182 |
class MyObject(GObject.Object): |
| 183 |
|
| 184 |
__gproperties__ = { |
| 185 |
'int-prop': ( |
| 186 |
int, # type |
| 187 |
'integer prop', # nick |
| 188 |
'A property that contains an integer', # blurb |
| 189 |
1, # min |
| 190 |
5, # max |
| 191 |
2, # default |
| 192 |
GObject.ParamFlags.READWRITE # flags |
| 193 |
), |
| 194 |
} |
| 195 |
|
| 196 |
def __init__(self): |
| 197 |
super().__init__() |
| 198 |
self.int_prop = 2 |
| 199 |
|
| 200 |
def do_get_property(self, prop): |
| 201 |
if prop.name == 'int-prop': |
| 202 |
return self.int_prop |
| 203 |
else: |
| 204 |
raise AttributeError('unknown property %s' % prop.name) |
| 205 |
|
| 206 |
def do_set_property(self, prop, value): |
| 207 |
if prop.name == 'int-prop': |
| 208 |
self.int_prop = value |
| 209 |
else: |
| 210 |
raise AttributeError('unknown property %s' % prop.name) |
| 211 |
|
| 212 |
|
| 213 |
For this approach properties must be defined in the ``__gproperties__`` class |
| 214 |
attribute, a dictionary, and handled in :meth:`GObject.Object.do_get_property` |
| 215 |
and :meth:`GObject.Object.do_set_property` |
| 216 |
:ref:`virtual methods <virtual-methods>`. |
| 217 |
|
| 218 |
.. hint:: |
| 219 |
Changes to custom properties are also signaled by the ``notify`` detailed |
| 220 |
signal. But remember that it will normalize your property name to hyphens |
| 221 |
instead of underscores, so you will write ``notify::prop-int`` and not |
| 222 |
``notify::prop_int``. |
| 223 |
|
| 224 |
Signals |
| 225 |
------- |
| 226 |
Each signal is registered in the type system together with the type on which it |
| 227 |
can be emitted: users of the type are said to connect to the signal on a given |
| 228 |
type instance when they register a function to be invoked upon the signal |
| 229 |
emission. Users can also emit the signal by themselves or stop the emission of |
| 230 |
the signal from within one of the functions connected to the signal. |
| 231 |
|
| 232 |
Create new signals |
| 233 |
^^^^^^^^^^^^^^^^^^ |
| 234 |
|
| 235 |
New signals can be created by using the :func:`GObject.Signal` decorator. |
| 236 |
The decorated methods are the object method handlers, these will be called when |
| 237 |
the signal is emitted. |
| 238 |
|
| 239 |
The time at which the method handlers are invoked depends on the signal flags. |
| 240 |
:attr:`GObject.SignalFlags.RUN_FIRST` indicates that this signal will invoke the |
| 241 |
object method handler in the first emission stage. |
| 242 |
Alternatives are :attr:`GObject.SignalFlags.RUN_LAST` (the method handler will be |
| 243 |
invoked in the third emission stage) and :attr:`GObject.SignalFlags.RUN_CLEANUP` |
| 244 |
(invoke the method handler in the last emission stage). |
| 245 |
|
| 246 |
Signals can also have arguments, the number and type of each argument is defined |
| 247 |
as a tuple of types. |
| 248 |
|
| 249 |
Signals can be emitted using :meth:`GObject.Object.emit`. |
| 250 |
|
| 251 |
.. code:: python |
| 252 |
|
| 253 |
from gi.repository import GObject |
| 254 |
|
| 255 |
class MyObject(GObject.Object): |
| 256 |
|
| 257 |
def __init__(self): |
| 258 |
super().__init__() |
| 259 |
|
| 260 |
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(int,)) |
| 261 |
def arg_signal(self, number): |
| 262 |
"""Called every time the signal is emitted""" |
| 263 |
print('number:', number) |
| 264 |
|
| 265 |
@GObject.Signal |
| 266 |
def noarg_signal(self): |
| 267 |
"""Called every time the signal is emitted""" |
| 268 |
print('noarg_signal') |
| 269 |
|
| 270 |
|
| 271 |
my_object = MyObject() |
| 272 |
|
| 273 |
def signal_callback(object_, number): |
| 274 |
"""Called every time the signal is emitted until disconnection""" |
| 275 |
print(object_, number) |
| 276 |
|
| 277 |
my_object.connect('arg_signal', signal_callback) |
| 278 |
my_object.emit('arg_signal', 100) # emit the signal "arg_signal", with the |
| 279 |
# argument 100 |
| 280 |
|
| 281 |
my_object.emit('noarg_signal') |
| 282 |
|
| 283 |
|
| 284 |
Alternatively you can use the more verbose `__gsignals__` class |
| 285 |
attribute to define signals. |
| 286 |
When a new signal is created, a method handler can also be defined in the form |
| 287 |
of ``do_signal_name``, it will be called each time the signal is emitted. |
| 288 |
|
| 289 |
.. code:: python |
| 290 |
|
| 291 |
class MyObject(GObject.Object): |
| 292 |
__gsignals__ = { |
| 293 |
'my_signal': ( |
| 294 |
GObject.SignalFlags.RUN_FIRST, # flag |
| 295 |
None, # return type |
| 296 |
(int,) # arguments |
| 297 |
) |
| 298 |
} |
| 299 |
|
| 300 |
def do_my_signal(self, arg): |
| 301 |
print("method handler for `my_signal' called with argument", arg) |
| 302 |
|
| 303 |
.. _virtual-methods: |
| 304 |
|
| 305 |
Virtual Methods |
| 306 |
--------------- |
| 307 |
|
| 308 |
GObject and its based libraries usually have gobjects that expose virtual |
| 309 |
methods. These methods serve to override functionality of the base gobject or |
| 310 |
to run code on a specific scenario. |
| 311 |
In that case you should call the base gobject virtual method to preserve its |
| 312 |
original behavior. |
| 313 |
|
| 314 |
In PyGObject these methods are prefixed with ``do_``. Some examples are |
| 315 |
:meth:`GObject.Object.do_get_property` or :meth:`Gio.Application.do_activate`. |
| 316 |
|
| 317 |
.. important:: |
| 318 |
The Python :py:class:`super` class only works for the immediate parent. |
| 319 |
If you want to chain some virtual method from a object that is more |
| 320 |
up in the hierarchy of the one you are subclassing you must call the method |
| 321 |
directly from the object class: |
| 322 |
``SomeOject.method(self, args)``. |
| 323 |
|
| 324 |
.. code:: python |
| 325 |
|
| 326 |
class SomeOject(OtherObject): |
| 327 |
... |
| 328 |
|
| 329 |
class MyObject(SomeOject): |
| 330 |
|
| 331 |
def __init__(self): |
| 332 |
super().__init__() |
| 333 |
|
| 334 |
def do_virtual_method(self): |
| 335 |
# Call the original method to keep its original behavior |
| 336 |
super().do_virtual_method() |
| 337 |
|
| 338 |
# Run some extra code |
| 339 |
... |
| 340 |
|
| 341 |
"""This is a virtual method from SomeOject parent""" |
| 342 |
def do_other(self): |
| 343 |
OtherObject.do_other(self) # We can't use super() |
| 344 |
... |