2

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 ?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Dadep
  • 2,796
  • 5
  • 27
  • 40

1 Answers1

2

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.

Community
  • 1
  • 1
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • thanks, I think i start to understand the idea. But when I try your short-term solution I get : `QApplication.processEvents() NameError: global name 'QApplication' is not defined` ...? – Dadep Dec 12 '16 at 17:38
  • @Dadep. You need to import it - or maybe use `QtGui.QApplication` (or `QtWidgets.QApplication` for PyQt5). – ekhumoro Dec 12 '16 at 17:49
  • It was a problem of `from PyQt4.QtCore import *, from PyQt4.QtGui import * ` ... Ah yes exactly ! (I was writing comment at the same time) Thanks – Dadep Dec 12 '16 at 17:50