Joshua Strot
Joshua Strot

Reputation: 2521

How do you implement multilingual support for pyqt4

I have a pyqt4 program and would like to implement multilingual support. I have all the .qm files, but can't figure out how to use them.

I can't really find much documentation on this, and nothing I try seems to work right.

Upvotes: 1

Views: 453

Answers (1)

ekhumoro
ekhumoro

Reputation: 120578

There's tons of documentation on this subject, which can be found in the obvious places:

Below is a simple demo script (run with -h for usage):

from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        message = self.tr('Hello World')
        label = QtGui.QLabel('<center><b>%s</b><center>' % message, self)
        buttonbox = QtGui.QDialogButtonBox(self)
        buttonbox.addButton(QtGui.QDialogButtonBox.Yes)
        buttonbox.addButton(QtGui.QDialogButtonBox.No)
        buttonbox.addButton(QtGui.QDialogButtonBox.Cancel)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(label)
        layout.addWidget(buttonbox)

if __name__ == '__main__':

    import sys, os, getopt

    options, args = getopt.getopt(sys.argv[1:], 'hl:')
    options = dict(options)
    if '-h' in options:
        print("""
Usage: %s [opts] [path/to/other.qm]

Options:
 -h        display this help and exit
 -l [LOC]  specify locale (e.g. fr, de, es, etc)
""" % os.path.basename(__file__))
        sys.exit(2)
    app = QtGui.QApplication(sys.argv)
    translator = QtCore.QTranslator(app)
    if '-l' in options:
        locale = options['-l']
    else:
        locale = QtCore.QLocale.system().name()
    # translator for built-in qt strings
    translator.load('qt_%s' % locale,
                    QtCore.QLibraryInfo.location(
                        QtCore.QLibraryInfo.TranslationsPath))
    app.installTranslator(translator)
    if args:
        # translator for app-specific strings
        translator = QtCore.QTranslator(app)
        translator.load(args[0])
        app.installTranslator(translator)
    window = Window()
    window.setGeometry(500, 300, 200, 60)
    window.show()
    sys.exit(app.exec_())

Upvotes: 4

Related Questions