Make a choice with a ComboBox, PyQT - pyqt

how are you ?
I just to create a programme wherein a propose a choice with Combobox.
For exemple, if you choice a item in a ComboBox, it will be write in a Spinbox.
But my probléme is that, to wirte in a third Spinbox without create a new Combobox.
Hope you understand
Check it out :)
`
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtCore import Qt
from PyQt4.QtGui import (QApplication, QWidget, QVBoxLayout, QSpinBox, QComboBox)
class Widget(QWidget):
def __init__(self):
super(Widget, self).__init__()
self.layout = QVBoxLayout(self)
self.spin = QSpinBox(self)
self.spin2 = QSpinBox(self)
self.spin3 = QSpinBox(self)
self.combo = QComboBox(self)
self.combo2 = QComboBox(self)
self.layout.addWidget(self.spin)
self.layout.addWidget(self.spin2)
self.layout.addWidget(self.spin3)
self.layout.addWidget(self.combo)
self.layout.addWidget(self.combo2)
self.combo.currentIndexChanged['QString'].connect(self.on_combo_changed)
self.combo2.currentIndexChanged['QString'].connect(self.changed)
self.data = {"HANDSET1": 5,"HANDSET": 6, "HANDFREE": 10, "CAR KIT": 15, "RSM": 20}
self.dodo = {"HANDSET1": 44, "HANDSET": 76, "HANDFREE": 1, "CAR KIT": 7, "RSM": 0}
self.coco = {"HANDSET1": 0, "HANDSET": 7, "HANDFREE": 11, "CAR KIT": 77, "RSM": 10} # How to put this function, without create a other ComboBox ?
self.combo.addItems(self.data.keys())
self.combo2.addItems(self.dodo.keys())
def on_combo_changed(self, txt):
self.spin.setValue(self.data[unicode(txt)])
def changed(self, txt):
self.spin2.setValue(self.coco[unicode(txt)])
if __name__ == '__main__':
app = QApplication([])
w = Widget()
w.show()
sys.exit(app.exec_())
`

Related

how to make a slider which has a label can show above the handle with pyside2

The current value could displayed immediately above the slider,such like this:
enter image description here
Thanks so much!
I had try like it but it show not good enough.
Here is my codes:
import sys
from PySide2.QtWidgets import QApplication, QWidget, QSlider, QLabel
from PySide2.QtCore import Qt
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.slider = QSlider(Qt.Horizontal, self)
self.slider.setRange(0, 100)
self.slider.setValue(50)
self.slider.setGeometry(30, 40, 100, 30)
self.slider.valueChanged[int].connect(self.changeValue)
self.label = QLabel(self)
self.label.setText("50")
self.label.setGeometry(140, 40, 30, 30)
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('QSlider')
self.show()
def changeValue(self, value):
self.label.setText(str(value))
self.label.move(self.slider.x() + value, self.slider.y() - 20)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWidget()
sys.exit(app.exec_())

How can I take a value from a line edit to another window's line edit by using Python and PyQt5?

What I need:
I need to create a simple project that can take value from window to another window
My research effort:
So, I create two classes for two windows then connect to classes with each other, so when I click in button it takes the value from 1st window then open the other window but the value=nothing because the clickMethod returns nothing.
Below is my code:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(320, 140))
self.setWindowTitle("First Window")
self.nameLabel = QLabel(self)
self.nameLabel.setText('1st:')
self.line = QLineEdit(self)
self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)
pybutton = QPushButton('OK', self)
pybutton.clicked.connect(self.second_wind) #connect button to open second window
pybutton.clicked.connect(self.clickMethod)
pybutton.resize(200,32)
pybutton.move(80, 60)
def clickMethod(self):
value =self.line.text() #take value from the line edit
return value
def second_wind(self): #object from secod_window class
self.SW = Second_Window()
self.SW.show()
class Second_Window(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(320, 140))
self.setWindowTitle("Second Window")
self.nameLabel = QLabel(self)
self.nameLabel.setText('Name:')
self.line = QLineEdit(self)
self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)
self.f = MainWindow() #make object from MainWindow class to execute clickMethod() to reutrn value
a=self.f.clickMethod()
print(a)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit( app.exec_() )
I expect the Clickmethod to return the value
but it returns nothing
Try it:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(320, 140))
self.setWindowTitle("First Window")
self.nameLabel = QLabel(self)
self.nameLabel.setText('1st:')
self.line = QLineEdit(self)
self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)
pybutton = QPushButton('OK', self)
pybutton.clicked.connect(self.second_wind)
# pybutton.clicked.connect(self.clickMethod)
pybutton.resize(200,32)
pybutton.move(80, 60)
# def clickMethod(self):
# value =self.line.text()
# return value
def second_wind(self):
text = self.line.text() # +++
self.SW = Second_Window(text) # +++ (text)
self.SW.show()
class Second_Window(QMainWindow):
def __init__(self, text): # +++ (text)
QMainWindow.__init__(self)
self.text = text # +
self.setMinimumSize(QSize(320, 140))
self.setWindowTitle("Second Window")
self.nameLabel = QLabel(self)
self.nameLabel.setText('Name:')
self.line = QLineEdit(self)
self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)
# self.f = MainWindow()
# a=self.f.clickMethod()
self.line.setText(self.text) # +
print(self.text)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit( app.exec_() )

QWidget raise above matplotlib canvas

I am working on a project on which I have a GUI (coded by hand) with two tabs, and on each tab I have a different canvas (to plot different things in each tabs).
But, I added also some widgets on these tabs and when I add them to the layout, if I add the canvas at the same position of a button in the layout for example, I can click on this button anymore.
I know on PyQt it is possible to raise the level of the widget, so is there a way to do the same thing with a canvas?
Thank you in advance for your help. On this example, the "Quit" is active only on the right half.
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
class FenetrePrincipale(QWidget):
def __init__(self, parent=None):
super(FenetrePrincipale, self).__init__(parent)
self.setupUi(self)
# Fonction de configuration de la classe
def setupUi(self, Form):
self.Form = Form
Form.setMinimumSize(1220, 850)
self.creation_GUI()
self.creation_figure()
self.creation_layout()
self.tabWidget.setCurrentIndex(0)
self.Bouton_quitter.clicked.connect(self.close)
def resizeEvent(self, QResizeEvent):
self.tabWidget.setMinimumSize(QSize(self.width() - 20, self.height() - 60))
def creation_GUI(self):
self.tabWidget = QTabWidget()
self.tab1 = QWidget()
self.Widget_choixPalette_Label = QLabel(self.tab1)
self.Widget_choixPalette_Label.setText("Text1")
self.Widget_choixPalette_ComboBox = QComboBox(self.tab1)
self.Widget_choixPalette_ComboBox.addItem("Try1")
self.Widget_choixPalette_ComboBox.addItem("Try2")
self.Bouton_quitter = QPushButton(self.tab1)
self.Bouton_quitter.setText("Quit")
def creation_layout(self):
LayoutForm = QGridLayout(self.Form)
LayoutG1 = QGridLayout()
LayoutTab1 = QGridLayout(self.tab1)
WidgetTemp = QWidget()
LayoutWidgetTemp = QGridLayout()
LayoutG1.addWidget(self.Bouton_quitter, 21, 29, 1, 2, Qt.AlignRight | Qt.AlignBottom)
LayoutG1.addWidget(self.canvas, 2, 10, 20, 20)
LayoutWidgetTemp.addWidget(self.Widget_choixPalette_Label, 0, 0, 1, 4)
LayoutWidgetTemp.addWidget(self.Widget_choixPalette_ComboBox, 1, 0, 1, 4)
WidgetTemp.setLayout(LayoutWidgetTemp)
LayoutG1.addWidget(WidgetTemp, 1, 18, 2, 4)
LayoutTab1.addLayout(LayoutG1, 0, 0, 1, 1)
self.tabWidget.addTab(self.tab1, " Tab1 ")
LayoutForm.addWidget(self.tabWidget, 1, 0, 1, 1)
def creation_figure(self):
# Create figure (transparent background)
self.figure = plt.figure()
self.figure.patch.set_facecolor('None')
self.canvas = FigureCanvas(self.figure)
self.canvas.setStyleSheet("background-color:transparent;")
# Adding one subplot for image
self.axe0 = self.figure.add_subplot(111)
self.axe0.get_xaxis().set_visible(False)
self.axe0.get_yaxis().set_visible(False)
plt.tight_layout()
# Data for init image
self.imageInit = [[255] * 320 for i in range(240)]
self.imageInit[0][0] = 0
# Init image and add colorbar
self.image = self.axe0.imshow(self.imageInit, interpolation='none')
divider = make_axes_locatable(self.axe0)
cax = divider.new_vertical(size="5%", pad=0.05, pack_start=True)
self.colorbar = self.figure.add_axes(cax)
self.figure.colorbar(self.image, cax=cax, orientation='horizontal')
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
# QApplication.setStyle(QStyleFactory.create("plastique"))
form = FenetrePrincipale()
form.show()
sys.exit(app.exec_())
Operating system: windows 7 Pro
Matplotlib version: 4.0.4
Matplotlib backend: Qt5Agg
Python version: 3.6
Other libraries: PyQt5
Edit 25/10/17 : new code for example
Below is a version of your example script that fixes all the issues. Most of the problems are caused by a very muddled use of layouts. I had to completely
re-write the creation_layout method in order to get a sane starting point so I could see where the problems were. I also temporarily restored the background colour of the canvas to make it easier to see how the widgets are layed out relative to each other. I realize that it won't be easy to incorporate some of my changes into your real code. But hopefully it will give you some ideas on how to simplify your layout structure.
The most important fix is the use of subplots_adjust in the creation_figure method. This removes all the empty space at the top of the canvas, so there is no longer any need to try to position other widgets on top of it.
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
class FenetrePrincipale(QWidget):
def __init__(self, parent=None):
super(FenetrePrincipale, self).__init__(parent)
self.setupUi(self)
# Fonction de configuration de la classe
def setupUi(self, Form):
self.Form = Form
Form.setMinimumSize(1220, 850)
self.creation_GUI()
self.creation_figure()
self.creation_layout()
self.tabWidget.setCurrentIndex(0)
self.Bouton_quitter.clicked.connect(self.close)
def resizeEvent(self, QResizeEvent):
self.tabWidget.setMinimumSize(QSize(self.width() - 20, self.height() - 60))
def creation_GUI(self):
self.tabWidget = QTabWidget()
self.tab1 = QWidget()
self.tabWidget.addTab(self.tab1, " Tab1 ")
self.Widget_choixPalette_Label = QLabel(self.tab1)
self.Widget_choixPalette_Label.setText("Text1")
self.Widget_choixPalette_ComboBox = QComboBox(self.tab1)
self.Widget_choixPalette_ComboBox.addItem("Try1")
self.Widget_choixPalette_ComboBox.addItem("Try2")
self.Bouton_quitter = QPushButton(self.tab1)
self.Bouton_quitter.setText("Quit")
def creation_layout(self):
LayoutForm = QGridLayout(self)
LayoutForm.addWidget(self.tabWidget, 0, 0, 1, 1)
LayoutTab1 = QGridLayout(self.tab1)
LayoutTab1.addWidget(self.Widget_choixPalette_Label, 0, 1, 1, 1)
LayoutTab1.addWidget(self.Widget_choixPalette_ComboBox, 1, 1, 1, 1)
self.Widget_choixPalette_ComboBox.setMinimumWidth(200)
LayoutTab1.addWidget(self.canvas, 2, 0, 1, 3)
LayoutTab1.addWidget(self.Bouton_quitter, 2, 3, 1, 1, Qt.AlignRight | Qt.AlignBottom)
LayoutTab1.setRowStretch(2, 1)
LayoutTab1.setColumnStretch(0, 1)
LayoutTab1.setColumnStretch(2, 1)
def creation_figure(self):
# Create figure (transparent background)
self.figure = plt.figure()
# self.figure.patch.set_facecolor('None')
self.canvas = FigureCanvas(self.figure)
self.canvas.setStyleSheet("background-color:transparent;")
# Adding one subplot for image
self.axe0 = self.figure.add_subplot(111)
self.axe0.get_xaxis().set_visible(False)
self.axe0.get_yaxis().set_visible(False)
# plt.tight_layout()
# Data for init image
self.imageInit = [[255] * 320 for i in range(240)]
self.imageInit[0][0] = 0
# Init image and add colorbar
self.image = self.axe0.imshow(self.imageInit, interpolation='none')
divider = make_axes_locatable(self.axe0)
cax = divider.new_vertical(size="5%", pad=0.05, pack_start=True)
self.colorbar = self.figure.add_axes(cax)
self.figure.colorbar(self.image, cax=cax, orientation='horizontal')
plt.subplots_adjust(left=0, bottom=0.05, right=1, top=1, wspace=0, hspace=0)
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
# QApplication.setStyle(QStyleFactory.create("plastique"))
form = FenetrePrincipale()
form.show()
sys.exit(app.exec_())
Just reverse the order you add things to the layout. Add the canvas first, then the button on top
LayoutForm.addWidget(canvas,1,0,1,6)
LayoutForm.addWidget(button,1,0,1,2)

PyQt5 Retrieve Folder Directory and Set It in lineEdit

Need some advice on how to retrieve the directory path for a selected folder and set it on the LineEdit.
I have the following simple GUI
If I clicked the toolButton (the button inside the red-circle), then a dialog window would pop up. Then we could navigate to select the desired folder. I wish that I could pass the path (in string) to the selected folder to the lineEdit box next to the button, once the user clicks Select Folder. However, I could not figure out how to do that. So far here is my code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_TestQFileDialog(object):
def _open_file_dialog(self): # a function to open the dialog window
result = str(QtWidgets.QFileDialog.getExistingDirectory())
print(result)
return result
def setupUi(self, TestQFileDialog):
TestQFileDialog.setObjectName("TestQFileDialog")
TestQFileDialog.resize(240, 320)
self.toolButtonOpenDialog = QtWidgets.QToolButton(TestQFileDialog)
self.toolButtonOpenDialog.setGeometry(QtCore.QRect(210, 10, 25, 19))
self.toolButtonOpenDialog.setObjectName("toolButtonOpenDialog")
directory = self.toolButtonOpenDialog.clicked.connect(self._open_file_dialog)
self.lineEdit = QtWidgets.QLineEdit(TestQFileDialog)
self.lineEdit.setEnabled(False)
self.lineEdit.setGeometry(QtCore.QRect(10, 10, 191, 20))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit.setText('{}'.format(directory))
self.retranslateUi(TestQFileDialog)
QtCore.QMetaObject.connectSlotsByName(TestQFileDialog)
def retranslateUi(self, TestQFileDialog):
_translate = QtCore.QCoreApplication.translate
TestQFileDialog.setWindowTitle(_translate("TestQFileDialog", "Dialog"))
self.toolButtonOpenDialog.setText(_translate("TestQFileDialog", "..."))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
TestQFileDialog = QtWidgets.QDialog()
ui = Ui_TestQFileDialog()
ui.setupUi(TestQFileDialog)
TestQFileDialog.show()
sys.exit(app.exec_())
Tried to include print in the _open_file_dialog function, and it printed the directory path. However, it was not returned and kept in the directory variable.
Any advice will be much appreciated.
Thanks and regards,
Arnold
Found the answer, the .setText method should be included in the _open_file_dialog function.
Therefore, the final code would look like this:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_TestQFileDialog(object):
def _open_file_dialog(self):
directory = str(QtWidgets.QFileDialog.getExistingDirectory())
self.lineEdit.setText('{}'.format(directory))
def _set_text(self, text):
return text
def setupUi(self, TestQFileDialog):
TestQFileDialog.setObjectName("TestQFileDialog")
TestQFileDialog.resize(240, 320)
self.toolButtonOpenDialog = QtWidgets.QToolButton(TestQFileDialog)
self.toolButtonOpenDialog.setGeometry(QtCore.QRect(210, 10, 25, 19))
self.toolButtonOpenDialog.setObjectName("toolButtonOpenDialog")
self.toolButtonOpenDialog.clicked.connect(self._open_file_dialog)
self.lineEdit = QtWidgets.QLineEdit(TestQFileDialog)
self.lineEdit.setEnabled(False)
self.lineEdit.setGeometry(QtCore.QRect(10, 10, 191, 20))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(TestQFileDialog)
QtCore.QMetaObject.connectSlotsByName(TestQFileDialog)
def retranslateUi(self, TestQFileDialog):
_translate = QtCore.QCoreApplication.translate
TestQFileDialog.setWindowTitle(_translate("TestQFileDialog", "Dialog"))
self.toolButtonOpenDialog.setText(_translate("TestQFileDialog", "..."))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
TestQFileDialog = QtWidgets.QDialog()
ui = Ui_TestQFileDialog()
ui.setupUi(TestQFileDialog)
TestQFileDialog.show()
sys.exit(app.exec_())
With QWidget
from PyQt5.QtWidgets import QWidget, QFileDialog,QDialog,QToolButton,QLineEdit,QVBoxLayout ,QGridLayout
class Ui_TestQFileDialog(QWidget):
def __init__(self,parent=None) -> None:
super(Ui_TestQFileDialog,self).__init__(parent)
self.setupUi()
self.show()
def _open_file_dialog(self,lineeditr):
directory = str(QFileDialog.getExistingDirectory())
lineeditr.setText('{}'.format(directory))
def _open_file_dialog1(self):
directory = str(QFileDialog.getExistingDirectory())
self.lineEdit1.setText('{}'.format(directory))
def _set_text(self, text):
return text
def setupUi(self):
# ------------------------- first set ------------------------------------------------------
TestQFileDialog = QDialog()
# TestQFileDialog.setObjectName("TestQFileDialog")
# TestQFileDialog.resize(240, 320)
self.toolButtonOpenDialog = QToolButton(TestQFileDialog)
# self.toolButtonOpenDialog.setGeometry(QtCore.QRect(210, 10, 25, 19))
# self.toolButtonOpenDialog.setObjectName("toolButtonOpenDialog")
self.lineEdit = QLineEdit(TestQFileDialog)
self.lineEdit.setEnabled(False)
# self.lineEdit.setGeometry(QtCore.QRect(10, 10, 191, 20))
# self.lineEdit.setObjectName("lineEdit")
self.lineEdit.textChanged.connect(self.prine_la)
self.toolButtonOpenDialog.clicked.connect(lambda: (self._open_file_dialog(self.lineEdit)))
# ----------------------------- second set --------------------------------------------------------
TestQFileDialog1 = QDialog()
# TestQFileDialog1.setObjectName("TestQFileDialog")
# TestQFileDialog1.resize(240, 320)
self.toolButtonOpenDialog1 = QToolButton(TestQFileDialog1)
# self.toolButtonOpenDialog1.setGeometry(QtCore.QRect(210, 10, 25, 19))
# self.toolButtonOpenDialog1.setObjectName("toolButtonOpenDialog")
self.lineEdit1 = QLineEdit(TestQFileDialog1)
self.lineEdit1.setEnabled(False)
self.lineEdit1.setPlaceholderText("Enter the gain value in between 0.0 to 23.05934920")
# self.lineEdit1.setGeometry(QtCore.QRect(10, 10, 191, 20))
# self.lineEdit1.setObjectName("lineEdit1")
self.toolButtonOpenDialog1.clicked.connect(lambda: (self._open_file_dialog(self.lineEdit1)))
self.retranslateUi(TestQFileDialog,self.toolButtonOpenDialog,"TestQFileDialog","data")
self.retranslateUi(TestQFileDialog1,self.toolButtonOpenDialog1,"TestQFileDialog1","data1")
QtCore.QMetaObject.connectSlotsByName(TestQFileDialog)
QtCore.QMetaObject.connectSlotsByName(TestQFileDialog1)
grid_layout = QGridLayout()
grid_layout.addWidget(self.lineEdit,0,0)
grid_layout.addWidget(self.toolButtonOpenDialog,0,1)
grid_layout.addWidget(self.lineEdit1,1,0)
grid_layout.addWidget(self.toolButtonOpenDialog1,1,1)
ve_box= QVBoxLayout()
# ve_box.addWidget(self.lineEdit)
# ve_box.addWidget(self.toolButtonOpenDialog)
# ve_box.addWidget(self.lineEdit1)
# ve_box.addWidget(self.toolButtonOpenDialog1)
ve_box.addLayout(grid_layout)
self.setLayout(ve_box)
def prine_la(self):
print(self.lineEdit.text())
def retranslateUi(self, TestQFileDialog,tool,dialogue:str,d: str):
_translate = QtCore.QCoreApplication.translate
TestQFileDialog.setWindowTitle(_translate(dialogue, d))
tool.setText(_translate(dialogue, "..."))
print("ANR .S")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Ui_TestQFileDialog()
sys.exit(app.exec_())

PyQT - Multiple languages QT Designer auto.generated UI

I am using PyQt4 and I want to translate my UI created with QT Designer in different languages. I follow some tutorials, but I am not able to apply my translation files.
I created a TS file, edited with QT Linguist and release a QM file. I try to apply it to my app, but it is still in source language.
This is retranslate method:
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))
And this is main:
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_())
Do you know what I am doing wrong?
There is probably some kind of issue with your code. See how this example works and adapt it to your needs:
#!/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_())
I have finally made it to fix it. The problem was the translated words context.
My class was named "Ui_Credentials" and my script "Credentials.py". The .bat that generated python code from QtDesigner automaticaly added "Ui_" prefix to my class.
The solution is to change my script name adding also "Ui_" prefix like "Ui_Credentials.py".
Thanks for the helps!

Resources