Issue
I have a simple programm where i want to switch languages at runtime. Since the GUI is not done with QtDesigner i dont have a .ui file and thus cannot use ui.retranslateUi as far as i can see. My current way of solving this is manually calling setText on every Widget every time a language change event occurs:
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class Simple(QPushButton):
def __init__(self):
super().__init__('translate-me')
self.translator = QTranslator()
self.clicked.connect(self.switchLanguage)
self.show()
def changeEvent(self, event):
if event.type() == QEvent.Type.LanguageChange:
self.setText(self.tr('translate-me'))
def switchLanguage(self):
self.translator.load('translation-file')
QApplication.installTranslator(self.translator)
app = QApplication(sys.argv)
simple = Simple()
sys.exit(app.exec_())
The solution with using ui.retranslateUi as described here is much shorter though. Is there a solution similar to that when not using a .ui file for the GUI?
Solution
The retranslateUi
method only affects objects created from the ui
file. So in order for it to provide a complete solution, every single string needing re-translation would have to be set in the ui file. Any strings added elsewhere would need entirely separate handling.
Here is an example of the retranslateUi
method:
def retranslateUi(self, Window):
self.fileMenu.setTitle(QtGui.QApplication.translate("Window", "&File", None, QtGui.QApplication.UnicodeUTF8))
self.helpMenu.setTitle(QtGui.QApplication.translate("Window", "&Help", None, QtGui.QApplication.UnicodeUTF8))
self.fileQuit.setText(QtGui.QApplication.translate("Window", "&Quit", None, QtGui.QApplication.UnicodeUTF8))
self.fileQuit.setShortcut(QtGui.QApplication.translate("Window", "Ctrl+Q", None, QtGui.QApplication.UnicodeUTF8))
self.helpAbout.setText(QtGui.QApplication.translate("Window", "&About", None, QtGui.QApplication.UnicodeUTF8))
self.helpAboutQt.setText(QtGui.QApplication.translate("Window", "About &Qt", None, QtGui.QApplication.UnicodeUTF8))
As you can see, all it does is call setText
(or whatever) on the affected objects it knows about. There is no magic involved. It's just boiler-plate code generated by the pyside-uic
tool.
If you can't use a ui
file, you will have to create something equivalent to the above yourself.
Answered By - ekhumoro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.