我正在创建一个带有组合框的简单窗口,让用户选择要在整个应用程序中显示的文本语言
我已经创建了必要的 .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,我将不胜感激。