1

我正在使用 PyQt4,我想用不同的语言翻译我用 QT Designer 创建的 UI。我遵循一些教程,但我无法应用我的翻译文件。

我创建了一个 TS 文件,用 QT Linguist 编辑并发布了一个 QM 文件。我尝试将它应用到我的应用程序中,但它仍然是源语言。

这是重新翻译方法:

def retranslateUi(self, CredentialsQT):
    CredentialsQT.setWindowTitle(QtGui.QApplication.translate("CredentialsQT", "IngeMaster", None, QtGui.QApplication.UnicodeUTF8))
    self.groupBox.setTitle(QtGui.QApplication.translate("CredentialsQT", "Credenciales de usuario", None, QtGui.QApplication.UnicodeUTF8))
    self.label.setText(QtGui.QApplication.translate("CredentialsQT", "Usuario:", None, QtGui.QApplication.UnicodeUTF8))
    self.label_2.setText(QtGui.QApplication.translate("CredentialsQT", "Contraseña:", None, QtGui.QApplication.UnicodeUTF8))
    self.groupBox_2.setTitle(QtGui.QApplication.translate("CredentialsQT", "Lenguaje", None, QtGui.QApplication.UnicodeUTF8))
    self.label_3.setText(QtGui.QApplication.translate("CredentialsQT", "Disponibles:", None, QtGui.QApplication.UnicodeUTF8))
    self.comboBox.setItemText(0, QtGui.QApplication.translate("CredentialsQT", "Deustch", None, QtGui.QApplication.UnicodeUTF8))
    self.comboBox.setItemText(1, QtGui.QApplication.translate("CredentialsQT", "English", None, QtGui.QApplication.UnicodeUTF8))
    self.comboBox.setItemText(2, QtGui.QApplication.translate("CredentialsQT", "Español", None, QtGui.QApplication.UnicodeUTF8))

这是主要的:

if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
archivo = 'Credentials_en.qm'

import os.path
if os.path.exists(archivo):
    print "El fichero existe"
else:
    print "El fichero no existe"

CredentialsQT = QtGui.QDialog()
ui = Ui_CredentialsQT()
ui.setupUi(CredentialsQT)

#from QtGui import QTranslator
translator=QtCore.QTranslator(app)
if translator.load(archivo, os.getcwd()):
    app.installTranslator(translator)

CredentialsQT.show()
sys.exit(app.exec_())

你知道我做错了什么吗?

4

2 回答 2

0

我终于把它修好了。问题是翻译的单词上下文。

我的班级被命名为“Ui_Credentials”,我的脚本被命名为“Credentials.py”。从 QtDesigner 生成 python 代码的 .bat 自动为我的类添加了“Ui_”前缀。

解决方案是更改我的脚本名称,同时添加“Ui_”前缀,如“Ui_Credentials.py”。

感谢您的帮助!

于 2013-09-27T10:15:30.960 回答
0

您的代码可能存在某种问题。查看此示例的工作原理并根据您的需要进行调整:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

#---------
# IMPORT
#---------
import sys, os, re

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtGui, QtCore

#---------
# DEFINE
#---------
class MyWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.languageDirectory  = "/usr/share/qt4/translations/"
        self.languageLocale     = "en"
        self.languageTranslator = QtCore.QTranslator()

        self.centralWidget = QtGui.QWidget(self)

        self.labelLanguageSelect = QtGui.QLabel(self.centralWidget)
        self.labelLanguageChange = QtGui.QLabel(self.centralWidget)

        self.comboBoxLanguage = QtGui.QComboBox(self.centralWidget)
        self.comboBoxLanguage.addItem("en" , "")

        for filePath in os.listdir(self.languageDirectory):
            fileName  = os.path.basename(filePath)
            fileMatch = re.match("qt_([a-z]{2,}).qm", fileName)
            if fileMatch:
                self.comboBoxLanguage.addItem(fileMatch.group(1), filePath)

        self.sortFilterProxyModelLanguage = QtGui.QSortFilterProxyModel(self.comboBoxLanguage)
        self.sortFilterProxyModelLanguage.setSourceModel(self.comboBoxLanguage.model())

        self.comboBoxLanguage.model().setParent(self.sortFilterProxyModelLanguage)
        self.comboBoxLanguage.setModel(self.sortFilterProxyModelLanguage)
        self.comboBoxLanguage.currentIndexChanged.connect(self.on_comboBoxLanguage_currentIndexChanged)
        self.comboBoxLanguage.model().sort(0)

        self.buttonBox = QtGui.QDialogButtonBox(self.centralWidget)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Yes|QtGui.QDialogButtonBox.Cancel)
        self.buttonBox.clicked.connect(self.on_buttonBox_clicked)

        self.layoutGrid = QtGui.QGridLayout(self.centralWidget)
        self.layoutGrid.addWidget(self.labelLanguageSelect, 0, 0, 1, 1)
        self.layoutGrid.addWidget(self.comboBoxLanguage, 0, 1, 1, 1)
        self.layoutGrid.addWidget(self.labelLanguageChange, 1, 0, 1, 1)
        self.layoutGrid.addWidget(self.buttonBox, 1, 1, 1, 1)

        self.setCentralWidget(self.centralWidget)
        self.retranslateUi()
        self.resetLanguage()
        self.updateButtons()

    @QtCore.pyqtSlot()
    def on_comboBoxLanguage_currentIndexChanged(self):
        self.setLanguage()
        self.updateButtons()

    def changeEvent(self, event):
        if event.type() == QtCore.QEvent.LanguageChange:
            self.retranslateUi()

        super(MyWindow, self).changeEvent(event)

    @QtCore.pyqtSlot(QtGui.QAbstractButton)
    def on_buttonBox_clicked(self, button):
        buttonRole = self.buttonBox.buttonRole(button)

        if buttonRole == QtGui.QDialogButtonBox.YesRole:
            self.languageLocale = self.comboBoxLanguage.currentText()
            self.updateButtons()

        elif buttonRole == QtGui.QDialogButtonBox.RejectRole:
            self.resetLanguage()

    def resetLanguage(self):
        index = self.comboBoxLanguage.findText(self.languageLocale)
        self.comboBoxLanguage.setCurrentIndex(index)

    def setLanguage(self):
        app = QtGui.QApplication.instance()
        app.removeTranslator(self.languageTranslator)

        languageIndex      = self.comboBoxLanguage.currentIndex()
        languageFileName   = self.comboBoxLanguage.itemData(languageIndex, QtCore.Qt.UserRole)

        if languageFileName != "en":
            languageFilePath = os.path.join(self.languageDirectory, languageFileName)
        else:
            languageFilePath = ""

        self.languageTranslator = QtCore.QTranslator()

        if self.languageTranslator.load(languageFilePath):
            app.installTranslator(self.languageTranslator)

    def updateButtons(self):
        state = self.languageLocale != self.comboBoxLanguage.currentText()

        self.buttonBox.button(QtGui.QDialogButtonBox.Cancel).setEnabled(state)
        self.buttonBox.button(QtGui.QDialogButtonBox.Yes).setEnabled(state)

    def retranslateUi(self):
        # This text is not included in te .qm file.
        # You'll have to create your own .qm file specifying the translation,
        # otherwise it won't get translated.

        self.labelLanguageSelect.setText(self.tr("Select Language:"))
        self.labelLanguageChange.setText(self.tr("Change Language:"))

#---------
# MAIN
#---------
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.resize(333, 111)
    main.show()

    sys.exit(app.exec_())
于 2013-09-26T21:45:12.077 回答