Search code examples
pythonprogress-barmainwindow

Update progress bar from sub-routine


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.


Solution

  • 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