【问题标题】:PyQT - Multiple languages QT Designer auto.generated UIPyQT - 多语言 QT Designer 自动生成的 UI
【发布时间】:2013-10-02 16:35:13
【问题描述】:

我正在使用 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_())

你知道我做错了什么吗?

【问题讨论】:

    标签: pyqt qt-designer


    【解决方案1】:

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

    #!/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_())
    

    【讨论】:

    • Por fin he conseguido solucionarlo。 El problema era el contexto de las palabras traducidas。 Mi clase se llamaba“Ui_Credentials”和我的脚本“Credentials.py”。 La utilidad de QtDesigner me añade automáticamente el prefijo "Ui_" a las clases。 La solución que he encontrado es cambiar el nombre de mi script y añadirle también el prefijo "Ui_"。 Gracias por la ayuda!
    【解决方案2】:

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

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

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

    感谢您的帮助!

    【讨论】:

      猜你喜欢
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 2022-12-02
      • 2017-07-01
      相关资源
      最近更新 更多