(This is the fourth part of a series about custom widgets in GTK 4. Part 1, part 2, part 3).
Event handlers take over
In the previous parts, we’ve seen a few examples where handling GtkWidget signals was replaced by some auxiliary objects. This trend is even stronger in the input area, where we’ve traditionally had a number of signals to handle: ::button-press-event, ::key-press-event, ::touch-event, and so on. All of these signals are gone in GTK 4, and instead you are expected to add event controllers to your widget, and listen to their signals. For example, there are GtkGestureClick, GtkEventControllerKey, GtkGestureLongPress, and many more.
Event controllers can be created in ui files, but it is more common to do that in the init() function:
static void click_cb (GtkGestureClick *gesture, int n_press, double x, double y) { GtkEventController *controller = GTK_EVENT_CONTROLLER (gesture); GtkWidget *widget = gtk_event_controller_get_widget (controller); if (x < gtk_widget_get_width (widget) / 2.0 && y < gtk_widget_get_height (widget) / 2.0) g_print ("Red!\n"); } ... controller = gtk_gesture_click_new (); g_signal_handler_connect (controller, "pressed", G_CALLBACK (click_cb), NULL); gtk_widget_add_controller (widget, controller);
gtk_widget_add_controller() takes ownership of the controller and GTK cleans controllers up automatically when the widget is finalized, so there is nothing more to do.
Complex event handlers
The examples of event handlers in the previous sections are simple and handle only individual events, one at a time. Gestures are a bit more involved, since they handle sequences of related events, and generally keep state.
Examples of much more complex event handlers include things like DND, and keyboard shortcuts. We may cover some of these in a later article.
Going deeper
The unifying principle behind all the different event handlers is that GTK propagates the events it receives from the windowing system from the root of the widget tree to a target widget, and back up again, in a pattern commonly referred to as capture-bubble.
In the case of keyboard events, the target widget is the current focus. For pointer events, it is the hovered widget under the pointer.
To read more about input handling in GTK, visit the input handling overview in the GTK documentation.
Outlook
We’ve reached the end of the prepared material for this series. It may continue at some point in the future, if there is interest. Possible topics include: shortcuts, actions and activation, drag-and-drop, focus handling, or accessibility.