Jérôme
Jérôme

Reputation: 14674

PyQt: translate module strings at runtime

Strings in QObjects are translated at runtime. If the translator is changed, all those strings are refreshed. However, strings declared at module level or even static class attributes, are translated at import time.

I can see 3 ways of allowing module strings to be translated, none of which seems totally satisfying to me :

Is there a clean way of doing this ?

Upvotes: 4

Views: 2939

Answers (1)

ekhumoro
ekhumoro

Reputation: 120608

I think what you're looking for is QT_TR_NOOP (or QT_TRANSLATE_NOOP if you need to provide context).

This will mark a string literal as needing translation (i.e. so that it is picked up by pylupdate), but it does not do any translation at runtime (nor import time).

Thus:

from PyQt4.QtCore import QT_TR_NOOP

some_string = QT_TR_NOOP('Hello World')

class SomeClass(QObject):
    def do_something(self):
        print(self.tr(some_string))

The tr() here will translate some_string dynamically at runtime, but it will itself be ignored by pylupdate because it does not contain a string literal.

Note that QT_TR_NOOP could be aliased to the name tr in python (or you could just define your own dummy tr function), because pyludate only ever does static analysis:

from PyQt4.QtCore import QT_TR_NOOP as tr

some_string = tr('Hello World')

You can also use a true alias (i.e. something other than tr, translate, __tr, etc), by using the corresponding pylupdate option:

pylupdate -tr-function FOO file.pro

Upvotes: 4

Related Questions