Step by step, it’s time to skip a lot of boring explainations and just start with examples quickly:
self.tr()
Use self.tr() to surround all strings needed to be translated in Python code. (Must be in a QWidget class). For example:
1 | from PyQt4 import QtCore, QtGui |
QTranslator()
Take zh_TW for example, install QTranslator() in QApplication(). Use QTranslator().load() to load translate file.
bool QTranslator.load (self, QString fileName, QString directory = QString(), QString searchDelimiters = QString(), QString suffix = QString())
bool QTranslator.load (self, QLocale locale, QString fileName, QString prefix = QString(), QString directory = QString(), QString suffix = QString())
Notice: the file QTranslator loads is a
.qmfile (a binary file generate from.ts), instead of a.ts.
1 | translator = QtCore.QTranslator() |
Get System Locale Information
- QTranslator Class Reference
- QLocale Class Reference
Beside to os.getenv(), you can also get current system’s locale name with QtCore.QLocale.system().name(), its return value is a string like ja_JP. So you can load translation file by system’s locale:
1 | print('Localization loaded: ' |
pylupdate To Create .ts File
Now create a directory translate/, then use pylupdate to generate an empty .ts file in it for your PyQt file:
$ pylupdate4 main.py -ts translate/zh_TW.ts
Time To Translate!
Open translate/zh_TW.ts with Qt Linguist and begin to translate.
you can also use your prefered text editor to edit the file directly, because it’s just a XML file.
lrelease To Convert .ts into .qm
After finishing the translating, use lrelease to generate .qm binary file from .ts.
$ lrelease translate/zh_TW.ts
Updating 'translate/zh_TW.qm'...
Generated 55 translation(s) (55 finished and 0 unfinished)
But, How To Update Translation File?
After modifying strings in PyQt file, updating the translation file is necessary.
First, use pylupdate to update .ts file:
$ pylupdate4 main.py -ts translate/zh_TW.ts
Now you can open the .ts file with Qt Linguist to update old translations. After that, use lrelease again to generate .qm.
$ lrelease translate/zh_TW.ts
Updating 'translate/zh_TW.qm'...
Generated 56 translation(s) (56 finished and 0 unfinished)
At last, maybe you want to totally remove the unused/obsoleted translation items in
.tsfile, use-noobsoleteoption to do this:
$ pylupdate4 main.py -ts -noobsolete translate/zh_TW.ts