如何使用 pyqt5 从 __init__() 函数外部更新字段

How does one update a field from outside the __init__() function with pyqt5

我正在读取传感器并希望使用 PyQt5 在 GUI 中将其输出显示为十进制数。我找到了许多指出 label.setText('myStr') 函数的教程。但是,这不适用于我的设置,因为我需要根据另一个函数的输入更新该字段。我对 PyQt5 还不是很熟悉,如果能深入了解应该如何解决这个问题,我将不胜感激。 注意:(我正在使用 LCM 从 Raspberry Pi 获取数据。我不确定这是否与问题相关,但它有助于解释我下面的代码。)

这是我正在尝试做的事情:

class Home_Win(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        loadUi("sensor_interface.ui", self)
        self.label_temp.setText('temperature') #Just to verify that I can change it from here

    def acquire_sensors(self):
        temp = 0  #Make variable available outside nested function
        def listen(channel, data):
            msg=sensor_data.decode(data)
            temp = msg.temperature

        lc = lcm.LCM()
        subscription = lc.subscribe("sensor_data_0", listen)

            while True:
                lc.handle()
                self.label_temp.setText(str(temp))

关于如何更新 GUI 以显示我从传感器获得的读数有什么想法吗? 谢谢!

你快到了。您需要做的就是将 ui 保存在 __init__:

中的实例变量中
self.ui = loadUi("sensor_interface.ui", self) 

然后,假设 label_temp 是您的 QLabel 小部件的名称,只需执行:

self.ui.label_temp.setText(str(temp))

原来我需要添加repaint()。我也切换到 QLineEdit,因为这似乎对我来说效果更好。所以在 while 循环中我现在有:

self.ui.lineEdit_temp.setText(str(temp))
self.ui.lineEdit_temp.repaint()

这现在在读取数据流时将实时更新输出到 GUI。