2013-09-26 56 views
1

我使用的是PyQt4,我想翻譯用QT Designer在不同語言中創建的用戶界面。我遵循一些教程,但我無法申請我的翻譯文件。PyQT - 多語言QT設計器auto.generated 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_()) 

你知道我在做什麼錯?

回答

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_()) 
+0

Por fin he conseguido solucionarlo。 El problema era el contexto de las palabras traducidas。 Mi clase se llamaba「Ui_Credentials」y me script「Credentials.py」。 La utilidad de QtDesigner meañadeautomáticamenteel prefijo「Ui_」a las clases。 Lasoluciónque he encontrado es cambiar el nombre de mi script yañadirletambiénel prefijo「Ui_」。 Gracias por la ayuda! – user2257190

0

我終於做了它來解決它。問題在於翻譯文字的上下文。

我的課被命名爲「Ui_Credentials」,我的腳本「Credentials.py」。從QtDesigner自動生成python代碼的.bat爲我的類添加了「Ui_」前綴。

解決方法是更改​​我的腳本名稱,並添加「Ui_」前綴,如「Ui_Credentials.py」。

感謝您的幫助!