2

我正在创建一个带有组合框的简单窗口,让用户选择要在整个应用程序中显示的文本语言

我已经创建了必要的 .qm 文件,并且在我启动应用程序时正在更新文本。但是如何将它链接到组合框上的选项,并从主窗口中动态更改语言?

我的代码:

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

'''
GUI

'''

import sys
import os.path as osp
import os
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QWidget):

    def __init__(self):
        super(MainWindow,self).__init__()

        # Set MainWindow geometry, use settings of last session. If it's first session,
        # use defaulted settings
        self.settings = QtCore.QSettings('Paul',QtCore.QSettings.NativeFormat)
        self.resize(self.settings.value("size", QtCore.QSize(500, 300)).toSize())
        self.move(self.settings.value("pos", QtCore.QPoint(5, 5)).toPoint());

        self.initUI()


    def closeEvent(self, e):
        #Save MainWindow geometry session when closing the window
        self.settings.setValue("size",self.size())
        self.settings.setValue("pos",self.pos())
        e.accept()

    def initUI(self):

        self.hbox = QtGui.QVBoxLayout(self) # Create Vertival box layout to put the buttons
        self.myButtons = QtGui.QPushButton('button',self) #create push button
        self.myButtons.setStyleSheet("""QPushButton { background-color: red; font:bold 20px}""")
        self.myButtons.setToolTip('Push this button')
        self.myButtons.setText(self.tr('yes'))
        comboBox=QtGui.QComboBox(self) #create drop down menu
        comboBox.addItem('English')
        comboBox.addItem('Portugues')
        self.hbox.addWidget(comboBox,1,QtCore.Qt.AlignRight) #add drop down menu to box layout
        self.hbox.addStretch(3)      # set separation between buttons
        self.hbox.addWidget(self.myButtons,1,QtCore.Qt.AlignRight) #add button to box layout


        self.setWindowTitle('Test2')


        self.show()



def main():

    app = QtGui.QApplication(sys.argv)
    translator = QtCore.QTranslator()
    translator.load("~/translations/qt_pt.qm")
    app.installTranslator(translator)
    app.setWindowIcon(QtGui.QIcon(path)) 
    ex = MainWindow()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()   

基本上我想让组合框做这样的事情:

self.comboBox.currentIndexChanged.connect(self.combochange)

def combochange(self):
    if self.comboBox.currentText()=='Portugues':
        translator = QtCore.QTranslator() 
        translator.load('~/translations/qt_pt.qm')
        app.installTranslator(translator) #Obviously this doesn't work

我假设我必须以某种方式将参数从 mainWindow 传递给 main() 函数并重新加载所有内容。

这甚至可能吗?

OSX 10.11.6 上的 Python 2.7、QT 5.9.1、PyQt4 4.12.1

编辑:

我在 QT wiki 页面上发现了这篇文章,可以满足我的要求,不幸的是我根本不精通 C。如果有人能帮我把它翻译成python,我将不胜感激。

4

2 回答 2

1

这是一种更合适的方法:

#create a new translator and load the desired translation file
translator = QtCore.QTranslator()
translator.load("monAppli_fr.qm")

#install translator to the app 
#app is the variable created in (if __name__ == "__main__":) section, make it gloabl
app.installTranslator(translator)
#call retranslateUi on ui, which is defined in the same section as app
#MainWindow : created in the same section 
ui.retranslateUi(MainWindow)

就是这样,我的if __name__ == '__main__':部分看起来像:

if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
于 2017-11-30T16:06:01.083 回答
-1

好的,我找到了一种方法,我不知道它是否是一个非常“pythonic”的解决方案,但它确实有效

我的 main() 函数现在看起来像这样:

if __name__ == '__main__':
    lang =1 #default language
    i=0
    while i>=0:
        i=i+1
        if lang == 1:
            print "i'm english"
            if i>1:
                app2=None # to erase the previous aplication when we loop between two language choices
            app = QtGui.QApplication(sys.argv)
            translator = QtCore.QTranslator()
            translator.load("~/translations/qt_pt.qm")
            app.removeTranslator(translator)
            ex = MainWindow(lang)
            ex.show()
            lang =app.exec_()

        elif lang==0:
            print "i'm portuguese"
            app=None
            app2 = QtGui.QApplication(sys.argv)
            translator = QtCore.QTranslator()
            translator.load("~/translations/qt_pt.qm")
            app2.installTranslator(translator)
            ex = MainWindow(lang)
            ex.show()
            lang=app2.exec_()
            print "im here"

到现在我的应用程序需要加载哪种语言,在组合框中的用户输入之后,我定义了我的“combochange”函数,如下所示:

def combochange(self,e):
    #print self.comboBox.currentText()
    if self.comboBox.currentText()=="Portugues":
        MainWindow.lang=0
        QtGui.qApp.exit(MainWindow.lang)

    else:
        MainWindow.lang=1
        QtGui.qApp.exit(MainWindow.lang)

" lang" 在 my 之外传递mainWindow,这会触发一个应用程序关闭并以不同的语言重新打开。

它看起来不是很优雅,但它确实有效。

完整的代码是:

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

'''
GUI

'''

import sys
import os.path as osp
import os
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QWidget):

    def __init__(self,lang2):

        super(MainWindow,self).__init__()

        # Set MainWindow geometry, use settings of last session. If it's first session,
        # use defaulted settings
        self.settings = QtCore.QSettings('Paul',QtCore.QSettings.NativeFormat)
        self.resize(self.settings.value("size", QtCore.QSize(500, 300)).toSize())
        self.move(self.settings.value("pos", QtCore.QPoint(5, 5)).toPoint());

        self.initUI(lang2)

    def closeEvent(self, e):
        #Save MainWindow geometry session when closing the window
        self.settings.setValue("size",self.size())
        self.settings.setValue("pos",self.pos())
        e.accept()
        sys.exit()

    def initUI(self,lang2):

        self.hbox = QtGui.QVBoxLayout(self) # Create Vertival box layout to put the buttons
        self.myButtons = QtGui.QPushButton('button',self) #create push button
        self.myButtons.setStyleSheet("""QPushButton { background-color: red; font:bold 20px}""")
        self.myButtons.setToolTip('Push this button')
        #self.myButtons.setText(QtCore.QString(self.tr('yes')))
        self.myButtons.setText(self.tr("yes"))
        self.comboBox=QtGui.QComboBox(self) #create drop down menu
        if lang2 == 1:
            self.comboBox.addItem('English')
            self.comboBox.addItem('Portugues')
        else:
            self.comboBox.addItem('Portugues')
            self.comboBox.addItem('English')            
        self.comboBox.currentIndexChanged.connect(self.combochange)
        self.hbox.addWidget(self.comboBox,1,QtCore.Qt.AlignRight) #add drop down menu to box layout
        self.hbox.addStretch(3)      # set separation between buttons
        self.myButtons.clicked.connect(self.buttonClicked) # what should the button do
        self.hbox.addWidget(self.myButtons,1,QtCore.Qt.AlignRight) #add button to box layout

        self.setWindowTitle('Test2')

    def combochange(self,e):
        #print self.comboBox.currentText()
        if self.comboBox.currentText()=="Portugues":
            MainWindow.lang=0
            QtGui.qApp.exit(MainWindow.lang)

        else:
            MainWindow.lang=1
            QtGui.qApp.exit(MainWindow.lang)

    def buttonClicked(self):

        msbox= QtGui.QMessageBox()
        choice=msbox.warning(self,'ok',"This button doesn't do anything!!!")

        if choice == QtGui.QMessageBox.No:
            print('nanan')
        else:
            print('Bye')
            self.settings.setValue("size",self.size());
            self.settings.setValue("pos",self.pos());
            sys.exit()

if __name__ == '__main__':
    lang =1
    i=0
    while i>=0:
        i=i+1
        print i
        if lang == 1:
            print "i'm english"
            if i>1:
                app2=None
            app = QtGui.QApplication(sys.argv)
            translator = QtCore.QTranslator()
            translator.load("/Users/paulmota/Documents/BlueBerryProject/basefiles/translations/qt_pt.qm")
            app.removeTranslator(translator)
            ex = MainWindow(lang)
            ex.show()
            lang =app.exec_()

        elif lang==0:
            print "i'm portuguese"
            app=None
            app2 = QtGui.QApplication(sys.argv)
            translator = QtCore.QTranslator()
            translator.load("/Users/paulmota/Documents/BlueBerryProject/basefiles/translations/qt_pt.qm")
            app2.installTranslator(translator)
            ex = MainWindow(lang)
            ex.show()
            lang=app2.exec_()
            print "im here"
于 2017-09-06T14:25:27.640 回答