How to achieve internationalization in PyQt5?

In PyQt5, implementing internationalization can be achieved by following these steps:

  1. Create translation files: Start by making translation files for different languages. You can use the Qt Linguist tool to create and edit translation files (.ts files).
  2. Edit translation files using Qt Linguist: Open the Qt Linguist tool, open the file that needs to be translated, then add the fields that need to be translated along with their corresponding translations. Save the translation file as a .ts format.
  3. Compile translation files: convert .ts files into .qm files so that the program can load and use these translations.
  4. Load translation files in a PyQt5 program: Use the QTranslator class in a PyQt5 program to load translation files and translate the interface elements of the program into the corresponding language.

Here is a simple sample code demonstrating how to implement internationalization in PyQt5.

import sys
from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtCore import QTranslator, QLocale

app = QApplication(sys.argv)

translator = QTranslator()
translator.load("translation_file.qm")  # 加载翻译文件

app.installTranslator(translator)  # 安装翻译

label = QLabel("Hello World!")
label.show()

sys.exit(app.exec_())

In the example above, we loaded a translation file “translation_file.qm” and installed it into the application. This way, the “Hello World!” string in the program will be translated into the corresponding language. You can adjust the translation file and interface elements to achieve more complex internationalization effects according to your needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *