Debian Codegraph @

docs/guide/api/signals.rst

raw
1 .. currentmodule:: gi.repository
2
3 =======
4 Signals
5 =======
6
7 GObject signals are a system for registering callbacks for specific events.
8
9 To find all signals of a class you can use the
10 :func:`GObject.signal_list_names` function:
11
12
13 .. code:: pycon
14
15 >>> GObject.signal_list_names(Gio.Application)
16 ('activate', 'startup', 'shutdown', 'open', 'command-line', 'handle-local-options')
17 >>>
18
19
20 To connect to a signal, use :meth:`GObject.Object.connect`:
21
22 .. code:: pycon
23
24 >>> app = Gio.Application()
25 >>> def on_activate(instance):
26 ... print("Activated:", instance)
27 ...
28 >>> app.connect("activate", on_activate)
29 17L
30 >>> app.run()
31 ('Activated:', <Gio.Application object at 0x7f1bbb304320 (GApplication at 0x5630f1faf200)>)
32 0
33 >>>
34
35 It returns number which identifies the connection during its lifetime and which
36 can be used to modify the connection.
37
38 For example it can be used to temporarily ignore signal emissions using
39 :meth:`GObject.Object.handler_block`:
40
41 .. code:: pycon
42
43 >>> app = Gio.Application(application_id="foo.bar")
44 >>> def on_change(*args):
45 ... print(args)
46 ...
47 >>> c = app.connect("notify::application-id", on_change)
48 >>> app.props.application_id = "foo.bar"
49 (<Gio.Application object at 0x7f1bbb304550 (GApplication at 0x5630f1faf2b0)>, <GParamString 'application-id'>)
50 >>> with app.handler_block(c):
51 ... app.props.application_id = "no.change"
52 ...
53 >>> app.props.application_id = "change.again"
54 (<Gio.Application object at 0x7f1bbb304550 (GApplication at 0x5630f1faf2b0)>, <GParamString 'application-id'>)
55 >>>
56
57
58 You can define your own signals using the :obj:`GObject.Signal` decorator:
59
60
61 .. function:: GObject.Signal(name='', flags=GObject.SignalFlags.RUN_FIRST, \
62 return_type=None, arg_types=None, accumulator=None, accu_data=None)
63
64 :param str name: The signal name
65 :param GObject.SignalFlags flags: Signal flags
66 :param GObject.GType return_type: Return type
67 :param list arg_types: List of :class:`GObject.GType` argument types
68 :param accumulator: Accumulator function
69 :type accumulator: :obj:`GObject.SignalAccumulator`
70 :param object accu_data: User data for the accumulator
71
72
73 .. code:: python
74
75 class MyClass(GObject.Object):
76
77 @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, return_type=bool,
78 arg_types=(object,),
79 accumulator=GObject.signal_accumulator_true_handled)
80 def test(self, *args):
81 print("Handler", args)
82
83 @GObject.Signal
84 def noarg_signal(self):
85 print("noarg_signal")
86
87 instance = MyClass()
88
89 def test_callback(inst, obj):
90 print "Handled", inst, obj
91 return True
92
93 instance.connect("test", test_callback)
94 instance.emit("test", object())
95
96 instance.emit("noarg_signal")