【问题标题】:PyQt get value from GUIPyQt 从 GUI 获取价值
【发布时间】:2018-11-17 13:53:21
【问题描述】:

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

我用一个带有两个项目和一个文本框的组合框做了一个简单的 GUI。我正在尝试读取组合框文本并根据所选项目设置文本框的文本。

这是我用来运行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))

有什么想法吗?

谢谢

【问题讨论】:

  • 在不修改从 .ui 生成的 .py 的情况下,您认为有什么更好的方法?
  • 这只是一个解释问题的示例,但完整的任务需要很长时间。

标签: python pyqt pyqt4 qthread


【解决方案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()

【讨论】:

  • 感谢您的帮助。它更新国家变量,但是当我将值传递给 updateText() 时,我得到:名称错误:未定义全局名称“国家/地区”。有什么建议吗?
  • 我已将 self.updated.emit(country) 修改为 self.updated.emit(str(country)) 并且现在可以使用。感谢您的帮助
  • 我一定会的。
猜你喜欢
  • 1970-01-01
  • 2017-08-15
  • 2017-01-08
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
  • 2020-07-16
  • 2013-04-11
相关资源
最近更新 更多