Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 218
Rafał Łużyński Avatar asked Feb 10 '26 21:02

Rafał Łużyński


1 Answers

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.

like image 66
piccy Avatar answered Feb 14 '26 05:02

piccy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!