问题
I've built an User Interface using QtDesigner
and then converted the .ui
to .py
. The User Interface has different comboBox
and textBox
from which I want to read the values once the Run button is clicked. Run a function and then populate other text boxes of the user interface once the calculations are completed. However when I change the value of the comboBox
and click the button the script still reads the initial value.
I did a simple GUI with a comboBox with two items and a textBox. I'm trying to read the the comboBox text and based on the selected item set the text of the textBox.
Here is the code I'm using to run the GUI
and read the value:
from PyQt4 import QtGui
from pyQt4 import QtCore
import sys
import GUI
class MyThread(QtCore.QThread):
updated = QtCore.pyqtSignal(str)
def run(self):
self.gui = Window()
name = self.gui.gui_Name.currentText()
print (name)
if name == 'Cristina':
country = 'Italy'
else:
country = 'Other'
self.updated.emit(str(1))
class Window(QtGui.QMainWindow, GUI.Home):
def __init__(self,parent = None):
super(Window,self).__init__(parent)
self.setupUi(self)
self._thread = MyThread(self)
self._thread.updated.connect(self.updateText)
self.update()
self.
self.pushButton.clicked.connect(self._thread.start)
def updateText(self,text):
self.Country.setText(str(country))
Any thoughts?
Thanks
回答1:
If the code that you implement in the run is the one that I think you are abusing the threads since with the currentTextChanged
signal it would be enough as I show below:
class Window(QtGui.QMainWindow, GUI.Home):
def __init__(self,parent = None):
super(Window,self).__init__(parent)
self.setupUi(self)
self.gui_Name.currentTextChanged.connect(self.onCurrentTextChanged)
def onCurrentTextChanged(self, text):
if if name == 'Cristina':
country = 'Italy'
else:
country = 'Other'
self.Country.setText(str(country))
On the other hand if the real code is a time-consuming task then the use of the threads is adequate. If the task takes as reference the value of the QComboBox
at the moment of pressing the button then it establishes that value as property of the thread, in your case you are creating a new GUI in another thread instead of using the existing GUI:
class MyThread(QtCore.QThread):
updated = QtCore.pyqtSignal(str)
def run(self):
name = self.currentText
print(name)
if name == 'Cristina':
country = 'Italy'
else:
country = 'Other'
self.updated.emit(country)
class Window(QtGui.QMainWindow, GUI.Home):
def __init__(self,parent = None):
super(Window,self).__init__(parent)
self.setupUi(self)
self._thread = MyThread(self)
self._thread.updated.connect(self.Country.setText)
self.pushButton.clicked.connect(self.start_thread)
def start_thread(self):
self._thread.currentText = self.gui_Name.currentText()
self._thread.start()
来源:https://stackoverflow.com/questions/50744783/pyqt-get-value-from-gui