Here is a naive application which contains two labels, a button, and a combobox for language selection. If the user changes the language, then every text will be updated to the corresponding language because all the translations are already human prepared in the method change_language
.
from PyQt5.QtCore import*
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.language = "English"
self.setWindowTitle("English Title")
self.layout = QVBoxLayout()
self.language_combobox = QComboBox()
self.language_combobox.addItems(["English", "French", "Chinese"])
self.layout.addWidget(self.language_combobox)
self.language_combobox.currentIndexChanged.connect(self.change_language)
self.label = QLabel("English Label")
self.layout.addWidget(self.label)
self.x = 67
self.label_with_variable = QLabel("English with variable " + str(self.x))
self.layout.addWidget(self.label_with_variable)
self.button = QPushButton("English Button")
self.layout.addWidget(self.button)
self.setLayout(self.layout)
def change_language(self):
self.language = self.language_combobox.currentText()
if self.language == "English":
self.setWindowTitle("English Title")
self.label.setText("English Label")
self.label_with_variable.setText("English with variable " + str(self.x))
self.button.setText("English Button")
elif self.language == "Chinese":
self.setWindowTitle("中文标题")
self.label.setText("汉字")
self.label_with_variable.setText("这句话里有变量 " + str(self.x))
self.button.setText("中文按钮")
elif self.language == "French":
self.setWindowTitle("Titre français")
self.label.setText("Texte français avec àéîöÆ")
self.label_with_variable.setText("Voici une variable " + str(self.x))
self.button.setText("Appuyez ici")
if __name__ == "__main__":
import sys
system_app = QApplication(sys.argv)
license = MyWidget()
license.show()
system_app.exec()
However, such a naive implementation is obviously inefficient if the project has a large scale. The website https://wiki.qt.io/How_to_create_a_multi_language_application introduces a different way. It uses .qm
files and QTranslator
. However, after searching online about .qm
files and QTranslator
, it is just not clear to me what I am supposed to do. Furthermore, the website I give here is not in Python
and I am having difficulty understanding it.
Therefore, I ask for a concrete Python
example that uses .qm
files and QTranslator
like in the above website (or any other way suitable for a large project) that does exactly what my code above does .