Skip to content

Instantly share code, notes, and snippets.

@abidibo
Last active March 14, 2018 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abidibo/099f42a0175171a62393183888d663af to your computer and use it in GitHub Desktop.
Save abidibo/099f42a0175171a62393183888d663af to your computer and use it in GitHub Desktop.
PyQt Stuff

PyQt5 Stuff

i18n

Install the following package

$ sudo apt-get install pyqt5-dev-tools

In my case it was also necessary to install this other package to use linguist command

$ sudo apt-get install qt4-dev-tools

Mark strings to be translated

import os
omport sys
from PyQt5 import QtCore
from pyQt5.QtWidgets import QMainWindow, QApplication

class MainWindow(QMainWindow):
  def __init__(self):
    super(MainWindow, self).__init__()
    # shortcut
    self.translate = QtCore.QCoreApplication.translate
    
  def my_method(self):
    # translate(context, str)
    mystring = self.translate('MainWindow', 'string to be translated')

Create translation files

  • create a file app.pro containing sources and destinations, i.e.:

    SOURCES += ../ottobackup.py
    SOURCES += ../dialog_settings.py
    SOURCES += ../dialog_info.py
    
    TRANSLATIONS += app_it.ts
    
  • generate the ts files:

    $ pylupdate5 app.pro
    
  • insert the translations:

    $ linguist app_it.ts
    
  • compile the translation files:

    $ lrelease app.pro
    

Apply translations

In the main part of the program

if __name__ == '__main__':
  app = QApplication(sys.argv)
  translator = QtCore.QTranslator(app)
  lc_path = os.path.join(
      os.path.dirname(os.path.realpath(__file__)), 'i18n',
      'ottobackup_%s.qm' % QtCore.QLocale.system().name()[:2])
  translator.load(lc_path)
  app.installTranslator(translator)
  main_window = MainWindow(application_data)
  sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment