无论在应用中选择哪种语言,我都试图翻译成特定语言。我试图不改变应用程序的语言,所以即使知道我不认为的应用程序也会帮助我。下面我有一个alwaysTranslate()方法,即使我在应用程序中卸载翻译器(或者在这种情况下我只是没有翻译器),我总是希望用翻译后的文本返回。
import sys
from os import getcwd
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setupUi(self)
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(556, 362)
self.verticalLayout = QtWidgets.QVBoxLayout(Form)
self.verticalLayout.setObjectName("verticalLayout")
self.lineEdit = QtWidgets.QLineEdit(Form)
self.label = QtWidgets.QLabel()
self.verticalLayout.addWidget(self.label)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout.addWidget(self.lineEdit)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
self.label.setText(_translate("Ui_Form", "something"))
# this is what I want to come back with a local translation
def alwaysTranslate(self):
qt_translator = QtCore.QTranslator()
m_langPath = getcwd()
qt_translator.load("test.qm", m_langPath)
_translate = QtCore.QCoreApplication.translate
print("should NOT be 'something': " + _translate("Ui_Form", "something"))
if __name__ == '__main__':
app = QApplication(sys.argv)
qt_translator = QtCore.QTranslator(app)
m_langPath = getcwd()
_translate = QtCore.QCoreApplication.translate
qt_translator.load("test.qm", m_langPath)
app.installTranslator(qt_translator)
print("should NOT be 'something': " + _translate("Ui_Form", "something"))
qt_translator.load("en.qm", m_langPath)
app.installTranslator(qt_translator)
print("should be 'something': " + _translate("Ui_Form", "something"))
ex = Ui_Form()
ex.alwaysTranslate()
sys.exit(app.exec_())
我的test.ts文件看起来像
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS><TS version="2.0" language="zh_TW" sourcelanguage="en_US">
<context>
<name>Ui_Form</name>
<message>
<location filename="test.py" line="58"/>
<source>something</source>
<translation>matters not</translation>
</message>
</context>
</TS>
当我运行它时,我得到以下
不应该是&#39;:事情不是 应该是什么&#39;:东西 不应该是&#39;某事
我想成为的最后一个&#39;重要的不是&#39;同样。
答案 0 :(得分:1)
我没有尝试过,但我认为这应该有效:
def alwaysTranslate(self):
qt_translator = QtCore.QTranslator()
m_langPath = getcwd()
qt_translator.load("test.qm", m_langPath)
# use local translator
_translate = qt_translator.translate
print("should NOT be 'something': " + _translate("Ui_Form", "something"))