Text input in GTK 4

To wrap up the recent series of posts about input topics, lets talk about text editing in GTK 4.

The simple: shortcuts

Maybe you just need to handle a few keys as editing commands, for example Ctrl-z to undo. In that case, you can just use a shortcut with an action, and set it all up in your widgets class_init:

/* install an undo action */ 
gtk_widget_class_install_action (widget_class,
                                  "text.undo", NULL,
                                  my_undo_func);

/* bind Ctrl-z to the undo action */
 gtk_widget_class_add_binding_action (widget_class,
                                      GDK_KEY_z, GDK_CONTROL_MASK,
                                      "text.undo", NULL);

The complex: a text editor

When you need full text editing, the best approach is to re-use one of the ready-made widgets in GTK for this purpose: one of the entries, or if you need a full-blown text editor, GtkTextView.

If none of the existing entries fit your use case, you can also wrap your own GtkEditable implementation around a GtkText widget, and get all the hard parts of a text editing widget for free. The GTK docs explain how to do that.

The middle ground

But what if you don’t want an entry, but still need to let your users enter individual Unicode characters such as ñ or Å conveniently? I’ll let you come up with a use case for this (although I have one in mind).

One thing you can do is to use a GtkIMContext directly, and let it process key events for you. The way this works is that you attach a key event controller to your widget and connect an input method context to it:

controller = gtk_event_controller_key_new ();
gtk_widget_add_controller (widget, controller);

im_context = gtk_im_multicontext_new ();
gtk_event_controller_key_set_im_context (controller, im_context);

Now key events that reach your widget will be passed to the input method context. Connect a handler to its ::commit signal to receive the completed input:

static void
commit_cb (GtkIMContext *context,
           const char   *str,
           DemoWidget   *demo)
{
  pango_layout_set_text (demo->layout, str, -1);
  pango_layout_set_attributes (demo->layout, NULL);
  gtk_widget_queue_draw (GTK_WIDGET (demo));
}

...

g_signal_connect (im_context, "commit",
                  G_CALLBACK (commit_cb), demo);

You can connect a similar handler to the ::preedit-changed signal to provide the user feedback during preedit like GtkEntry does.

The complete example for single-character input can be found here.