PyQt internationalization

拈花ヽ惹草 提交于 2019-12-24 03:43:32

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14715015/pyqt-internationalization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!