PyQt4 and Qt include a comprehensive set of tools for translating applications into local languages. For a full description, see the Qt Linguist Manual in the Qt documentation.
The process of internationalising an application comprises the following steps.
.tstranslation file for each language that the application is to be translated into. A
.tsfile is an XML file that contains the strings to be translated and the corresponding translations that have already been made. pylupdate4 can be run any number of times during development to update the
.tsfiles with the latest strings for translation.
.tsfiles with translations of the strings.
.qmfiles which are compact binary equivalents used by the application. If an application cannot find an appropriate
.qmfile, or a particular string hasn't been translated, then the strings used in the original source code are used instead.
.qmfiles, along with other application resources such as icons, in a Python module. This may make packaging and distribution of the application easier.
is PyQt4's equivalent to Qt's
and is used in exactly the same way. A Qt
project file is read that
specifies the Python source files and Qt Designer interface files from which
the text that needs to be translated is extracted. The
translation files that
creates if necessary) and are subsequently used by Qt Linguist.
pylupdate4 will only be included if your copy of Qt includes the XML 模块。
Qt implements internationalisation support through the
methods. Usually the
method is used to obtain
the correct translation of a message. The translation process uses a message
context to allow the same message to be translated differently.
actually generated by
and uses the hardcoded class name as the context.
On the other hand,
allows the context to be
Unfortunately, because of the way Qt implements
is not possible for PyQt4 to exactly reproduce its behaviour. The PyQt4
) uses the class name of the
instance as the context. The key difference, and the source of potential
problems, is that the context is determined dynamically in PyQt4, but is
hardcoded in Qt. In other words, the context of a translation may change
depending on an instance's class hierarchy. For example:
class A(QtCore.QObject): def hello(self): return self.tr("Hello") class B(A): pass a = A() a.hello() b = B() b.hello()
In the above the message is translated by
using a context of
, and by
using a context of
. In the equivalent C++
version the context would be
in both cases.
The PyQt4 behaviour is unsatisfactory and may be changed in the future. It is
be used in preference to
). This is guaranteed to work with current and
future versions of PyQt4 and makes it much easier to share message files
between Python and C++ code. Below is the alternative implementation of
class A(QtCore.QObject): def hello(self): return QtCore.QCoreApplication.translate("A", "Hello")