Search code examples
pythonqtpyqt5lcm

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


I am reading a sensor and want to display its output as a decimal number in a GUI using PyQt5. I have found a number of tutorials that point out the label.setText('myStr') function. This does not work for my setup, however, because I need to update the field based on the input from another function. I'm not very familiar with PyQt5 yet, and I would appreciate any insight into how this problem ought to be approached. Note: (I am using LCM to acquire data from a Raspberry Pi. I'm not sure that that is relevant to the problem, but it helps explain my code below.)

Here is what I am trying to do:

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

Any thoughts on how I can update the GUI to display the readings I am getting from my sensors? Thanks!


Solution

  • It turned out that I needed to add repaint(). I also switched to a QLineEdit as this seemed to work better for me. So inside the while loop I now have:

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

    This now outputs live updates to the GUI while reading the data stream.