Rafał Łużyński
Rafał Łużyński

Reputation: 7312

PyQt internationalization

I can transalate texts that comes from QtDesigner, but I can't translate anything that is defined outside it.

In example this code:

from PyQt4.QtCore import QCoreApplication
tr = QCoreApplication.translate


class Flag(object):

    def __init__(self, name):

        self._name = name
        self._setting_events = []
        self._clearing_events = []
        self._toggle_events = []
        self._true_name = tr("Flags", u'True')
        self._false_name = tr("Flags", u'False')

According to documentation first parameter is context and second is sourceText. But when I open my .ts file in QtLinguist, it shows that context is my sourceText and sourceText is a comment. Whatever, after translating it in QtLinguist I release .qm files and I run my app, but texts does not change. I see only passed sourceText, so in this example it's still 'True' and not what I translated.

What am I doing wrong?

Upvotes: 3

Views: 3536

Answers (2)

Jérôme
Jérôme

Reputation: 14664

I just fell in the same trap. piccy's comment above says it all.

pylupdate is "just" a file parser. It searches for tr() and translate() as strings. It ignores affectations such as my_tr_func = translate.

If you write

my_tr_func = translate
text = my_tr_func("Context", "Source text")

your string will be ignored.

The trick here is that you used tr() as an alias, not just any string, and instead of just ignoring it, pylupdate mistook it for the QObject tr() method and parsed its arguments accordingly.

There's nothing much you can do against this (unless you patch pylupdate...).

Note that apparently, you can write

translate = QtCore.QCoreApplication.translate
text = translate("Context", "Source text")

which is better than nothing.

Upvotes: 1

piccy
piccy

Reputation: 366

You need to load a translator before the translation function will work. You do that with code like the following:

translationFile = "<langfile>.qm"
translator = QtCore.QTranslator()
translator.load(translationFile, "<filepath>")
a.installTranslator(translator)

The a is the "app" object, which you create with code such as:

a = QtGui.qApp.instance()

This is generally done in the if __name__ == '__main__': block of your main Python file.

Upvotes: 2

Related Questions