August Karlstrom
August Karlstrom

Reputation: 11377

How do I make button label translations work in GTK?

I'm trying to make a simple dialog window in GTK 3 where the button labels are set in accordance with the chosen language.

Here is my program gtklocale.c:

#include <glib/gi18n.h>
#include <gtk/gtk.h>

int main(int argc, char *argv[])
{
    GtkWidget *dialog;

    gtk_init(&argc, &argv);

    dialog = gtk_dialog_new_with_buttons(
        "Title",
        NULL,
        0,
        _("_Cancel"),
        GTK_RESPONSE_CANCEL,
        _("_OK"),
        GTK_RESPONSE_OK,
        NULL);

    gtk_dialog_run(GTK_DIALOG(dialog));
    gtk_widget_destroy(dialog);
    return 0;
}

I compile this program with

gcc -Wall -o gtklocale -Wall $(pkg-config --cflags gtk+-3.0) gtklocale.c $(pkg-config --libs gtk+-3.0)

Here are my locales:

$ locale -a
C
C.UTF-8
en_US.utf8
POSIX
sv_SE.utf8

When I run the program as

LC_ALL=sv_SE.utf8 ./gtklocale

this dialog window is displayed:

enter image description here

I would expect "Cancel" to be translated into the Swedish word "Avbryt" but it isn't.

What is missing?

Upvotes: 2

Views: 559

Answers (1)

lb90
lb90

Reputation: 958

Here you are using the _() macro, i.e. direct g_gettext(), so the translations must be provided by your application; they will not be searched in libraries domains (libraries .mo files), but only in your application domain (that is, your application .mo file)

It's true that Gtk3 provides some 'stock' translated strings for use by applications, but they were deprecated in Gtk 3.10. From Gtk 3.10 on, it is recommended that applications provide their own translations of UI strings instead of relying on Gtk provided ones.

To reflect this, the devs updated the documentation for gtk_dialog_new_with_buttons: see the docs in Gtk 3.8 and Gtk 3.10 and compare. The new docs, simply put, are made to NOT make use of Gtk own translations!

Of course you can still make use of Gtk own translations, although deprecated, with one of the following ways:

  • Use stock identifiers in place of button labels:
dialog = gtk_dialog_new_with_buttons(
    "Title", NULL, 0,
    GTK_STOCK_CANCEL,
    GTK_RESPONSE_CANCEL,
    GTK_STOCK_OK,
    GTK_RESPONSE_OK,
    NULL);
  • Call g_dgettext() with "gtk30" domain:
dialog = gtk_dialog_new_with_buttons(
    "Title", NULL, 0,
    g_dgettext("gtk30", "_Cancel"),
    GTK_RESPONSE_CANCEL,
    g_dgettext("gtk30", "_OK"),
    GTK_RESPONSE_OK,
    NULL);

Hope it helps!

Upvotes: 2

Related Questions