Gtk.Builder does not localize/translate text

My program’s .ui file

<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <object class="GtkApplicationWindow" id="win">
    <property name="child">
      <object class="GtkLabel">
        <property name="label" translatable="yes">Label</property>
        <property name="height-request">40</property>
      </object>
    </property>
  </object>
</interface>

My program’s .py file

#!/usr/bin/python
import gettext
gettext.install('test-gtk-builder-l10n')

import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk

builder = Gtk.Builder.new_from_file('test-gtk-builder-l10n.ui')
win = builder.get_object('win')
win.set_title(_("Test Gtk.Builder internationalization support"))
app = Gtk.Application(application_id="org.example.l10n.test")
def on_activate(app):
    app.add_window(win)
    win.present()
app.connect('activate', on_activate)
app.run()

Values in my program’s ur.po file

#: ../test-gtk-builder-l10n.py:11
msgid "Test Gtk.Builder internationalization support"
msgstr "وِنڈو ٹائٹل"

#: ../test-gtk-builder-l10n.ui:6
msgid "Label"
msgstr "لیبل"

Result

Screenshot

Actual Question

Why is it that text written directly in python file gets translated but the text in interface definition file does not? Is this a bug in GTK4 or am I doing something wrong?

Note

I also tried settings Gtk.Builder's translation domain and adding _ at the start of translatable text in .ui file. None of these methods worked.

Your application is missing calls to bindtextdomain(), bind_textdomain_codeset(), and textdomain(). These are normally needed at the start of your application.

bind_textdomain_codeset() is deprecated, calling bindtextdomain() and textdomain() does not change the behavior.

I changed the line

gettext.install('test-gtk-builder-l10n')

to

gettext.bindtextdomain('test-gtk-builder-l10n', '/usr/share/locale')
gettext.textdomain('test-gtk-builder-l10n')
_ = gettext.gettext

as suggested by Python’s docs.

Label does not get translated and Window Title still gets translated.

Hmmm… OK sorry, I didn’t read your post closely enough anyway. Try gtk_builder_set_translation_domain(), or alternatively: <interface domain="test-gtk-builder-l10n> in the UI file. Hopefully one of those will work.

I decided to play along at home, and in my testing changing the <interface> tag in the .ui file to <interface domain="test-gtk-builder-l10n"> was enough to enable UI translations… however, the compiled translations also had to be installed as (for this example) /usr/share/locale/ur/LC_MESSAGES/test-gtk-builder-l10n.mo.

I couldn’t find any way to convince Gtk.Builder to load them from a different location, even if I provided a localedir= argument to gettext.install() or gettext.bindtextdomain(). Maybe there’s an environment variable that would’ve worked. :man_shrugging:

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.