How do you implement multilingual support for pyqt4

后端 未结 1 760
囚心锁ツ
囚心锁ツ 2021-01-24 05:29

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 docum

相关标签:
1条回答
  • 2021-01-24 06:24

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

    • Internationalization with Qt
    • Qt Linguist Manual
    • Internationalisation of PyQt4 Applications

    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_())
    
    0 讨论(0)
提交回复
热议问题