pythongtkgnome

Is there any difference between actions in GTK and using signals directly?


It seems that actions and signals are very similar. Is there any difference between them? Actions are higher level than signals?

For example, I want to press a button to do something, I can use action:

<object class="GtkButton">
  <property name="label">Start</property>
  <property name="action-name">app.start</property>
</object>
class xxxApplication(Adw.Application):
    def on_button_clicked(self,widget,_):
        print('Button pressed.')
    
    def create_action(self):
        action = Gio.SimpleAction.new("start", None)
        action.connect("activate", self.on_button_clicked)

I can also use signals directly:

  <object class="GtkButton">
    <property name="label">Start</property>
    <signal name="clicked" handler="on_button_clicked"/>
  </object>
class xxxWindow(Adw.ApplicationWindow):   
    @Gtk.Template.Callback()
    def on_button_clicked(self, button):
        print('Button pressed.')

Solution

  • Although the end result is the same, actions and signals have several differences. One of the main differences is that it is possible to add shortcuts to actions, but not to signals, at least not directly. Another important difference is that actions can be used directly on menu items, while signals are more difficult to use.

    In general, actions are made with reuse throughout the application in mind, while signals are used in more specific situations. If you need a function that will be triggered by a keyboard shortcut, a menu item and a button, you can solve this with three signals or with a single action.

    There are also differences in the parameters passed to the function, signals are more flexible than actions in this sense.