Search code examples
pythonwhile-looppyqtqtextedit

update text in a Qt interface from method not in main script


I want to call in my main program a method ExecuteM where in a while loop a text in my interface in Qt (call result), done with Qt creator will be update for each iteration.

class Machine():
    def __init__(self, result):
        self.result=result

    def ExecuteM(self, Var1, Var2):
        while Var1 != 'stop':
            Var2 = Var2 + 3
            self.result.setText(newResult())
            sleep(0.5)

then in my main script:

def main(self):
    self.TM=Machine(self.result)
    self.TM.ExecuteM(var1, var2)

but it does not work the text does not update at each iteration, why ?


Solution

  • If you execute a while-loop in the main thread, it will block the gui. All events will be queued until the while-loop terminates and control can return to the event-loop. So you either have to move the blocking while-loop into a separate thread, or periodically force the event-loop to process the pending events. In your example, it should probably be possible to achieve the latter like this:

        def ExecuteM(self, Var1, Var2):
            while Var1 != 'stop':
                Var2 = Var2 + 3
                self.result.setText(newResult())
                QApplication.processEvents()
                sleep(0.5)
    

    But that's just a short-term solution. It would probably be better to use a worker thread and send a custom signal back to the main thread.