Programming with Gtk2-Perl/Signals and Callbacks

Signals
The Gtk framework is event driven. This means it will remain idle in Gtk's main loop until an event occurs, at which point a signal will be emitted. If we have connected a callback to the signal, it will be executed before returning control back to the main loop.

In the last chapter we connected to the clicked signal of a button in order save some user input to a file.

Signal Connect
Here is the syntax of the signal_connect method which is provided in the Glib::Object base class - which all widgets inherit from. In addition to the name of the signal and callback, you may optionally pass in a scalar to be passed to the callback function when it is executed.

Callbacks
Callbacks are subroutine references that will be executed when a signal is emitted. When you define your callback function you will get the emitting widget and optionally a $data value as arguments.

Callbacks can also be anonymous subroutines. You can then use encapsulation to avoid passing in an argument. This approach is best used for short, simple callbacks. Take the example below.

Events
There also exists a set of events that you can connect callbacks to. Use the same signal_connect method in exactly the same manner as when connecting to signals. These events reflect the those of the x event mechanism. Here is a complete listing.

Callbacks
The callback function is slightly different for events.

The $event argument is an object that inherits from Gtk2::Gdk::Event. The actual package name will depend on the which event occurred. You can call the 'type' method on the $event to retrieve the type of event that occurred. You may also be able to call other methods on the $event that may be of interest, but that will vary depending on the type of event.

Event Types
Here is a list of possible values that could be returned from the type method.

Return Values
The value returned from your callback function determines whether events should be propagated further. Returning a TRUE value will stop the propagation of events, while a FALSE value will continue one with normal event handling.

Disconnecting and Blocking
By storing the Integer value returned from the 'signal_connect' method, we can disconnect the callback later.

You can also temporarily disable a callback from firing.