PyQt从GUI获取值

时间:2018-06-07 15:15:23

标签: python pyqt pyqt4 qthread

我使用QtDesigner构建了用户界面,然后将.ui转换为.py。用户界面具有不同的comboBoxtextBox,一旦单击“运行”按钮,我就会从中读取值。运行一个函数,然后在计算完成后填充用户界面的其他文本框。但是,当我更改comboBox的值并单击按钮时,脚本仍会读取初始值。

我使用带有两个项目和一个textBox的comboBox做了一个简单的GUI。我试图阅读comboBox文本,并根据所选项目设置textBox的文本。

以下是我用来运行GUI并读取值的代码:

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))

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:1)

如果您在运行中实现的代码是我认为您滥用线程的代码,那么使用currentTextChanged信号就足够了,如下所示:

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))

另一方面,如果真实代码是一项耗时的任务,那么使用线程就足够了。如果任务在按下按钮时将QComboBox的值作为参考,那么它将该值设置为线程的属性,在您的情况下,您将在另一个线程中创建新的GUI而不是使用现有的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()
相关问题