GtkAction – HowTo and Why

About

A problem that recently arose when I was developing a GTK application was I had a set of actions (New, Save, Open etc.) which needed to be in a ToolBar and a MenuBar.

The issue was keeping all these actions in sync, and it becomes even tricker when certain action are only enabled in certain scenarios.

However Gtk has an easy way to deal with this.

GtkAction

A GtkAction simply represents an action and it gives the opportunity for many widgets to make this action happen.

For example if I had a Save action, I would want my Save item in my Menubar and Toolbar do activate this action.

GtkAction also provides many more useful properties, besides just making the action happen. It can also store a label, tooltip, icon and more, so that each widget that uses the action simply ‘picks up’ this information.

In practice this means there is no need to set the label twice etc.

As well as the normal GtkAction class, there is also GtkToggleAction and GtkRadioAction (to represent actions that can be toggled, or a selection out of one) and GtkActionGroup so you can group together similar actions (i.e. actions that modify a document)

Howto use it

Glade

Create actions by clicking on the buttons under Actions

To set widgets to use them, configure the Related Action field

Code (Vala)


var action_clickme = new Gtk.Action("clickme", "Click Me!", "Why don't you click me?", Gtk.Stock.ABOUT);

// This widget can be anything that implement GtkActivatable
var button = new Gtk.Button();
button.set_related_action(action_clickme);
button.set_use_action_appearance(true);

action_clickme.activate.connect(() => {
stdout.printf("You activated the action!\n");
});

 

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

%d bloggers like this: