0

I would like to update a progress bar that I have on a main window with the progress of a task that I am doing on another sub-routine, would it be possible??

To be as clear as possible, I would have 2 files:

In my Mainwindow.py I would have something like:

import Calculations

#some code
self.ui.progressBar
Calculations.longIteration("parameters")

Then I would have a separate file for the calculations: Calculations.py

def longIteration("parameters")

#some code for the loop

"here I would have a loop running"
"And I would like to update the progressBar in Mainwindow"

Is that possible?

Or it should be done on a different way?

Thanks.

codeKiller
  • 5,493
  • 17
  • 60
  • 115

1 Answers1

1

The simplest of methods would be to simply pass the GUI object:

self.ui.progressBar
Calculations.longIteration("parameters", self.ui.progressBar)

and update progressBar on Calculations. This has two problems, though:

  • You're mixing GUI code with Calculations, who probably shouldn't know anything about it
  • if longIteration is a long running function, as its name implies, you're blocking your GUI main thread, which will make many GUI frameworks unhappy (and your application unresponsive).

Another solution is running longIteration in a thread, and pass a callback function that you use to update your progress bar:

import threading
def progress_callback():
    #update progress bar here
threading.Thread(target=Calculations.longIteration, args=["parameters", progress_callback]).run()

then, inside longIteration, do:

def longIteration( parameters, progress_callback ):
    #do your calculations
    progress_callback() #call the callback to notify of progress

You can modify the progress_callback to take arguments if you need them, obviously

loopbackbee
  • 21,962
  • 10
  • 62
  • 97
  • Hi Goncalopp, thanks for your answer. You are right about the first option. I took that first option because it looked easier for me, but, yes, the MainWindow becomes unresponsive, so the progressBar does not update until the end of the loop. So my problem with your second option, the one with a thread is that I do not fully understand how to update the progressBar with the progress of the loop from the thread – codeKiller Sep 22 '14 at 11:58
  • 1
    @newPyUser You need to call the callback from `longIteration`. I've edited the question to make it clear – loopbackbee Sep 22 '14 at 13:10