Report progress to QProgressBar using variable from an imported module
<p>I have a PyQT GUI application <code>progress_bar.py</code>with a single progressbar and an external module <code>worker.py</code> with a <code>process_files()</code> function which does some routine with a list of files and reports current progress using <code>percent</code> variable.</p>

<p>What I want to do is to report the current progress of the <code>worker.process_files</code> using <code>QProgressBar.setValue()</code> method, but I have no idea how to implement it (callback function or something?)</p>

<p>Here are my modules:</p>

<p><strong>progress_bar.py</strong></p>

<pre><code>import sys
from PyQt4 import QtGui
from worker import process_files


class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(100, 100, 300, 100)
        self.progress = QtGui.QProgressBar(self)
        self.progress.setGeometry(100, 50, 150, 20)
        self.progress.setValue(0)
        self.show()


app = QtGui.QApplication(sys.argv)
GUI = Window()
# process files and report progress using .setValue(percent)
process_files()
sys.exit(app.exec_())
</code></pre>

<p><strong>worker.py</strong></p>

<pre><code>def process_files():
    file_list = ['file1', 'file2', 'file3']
    counter = 0
    for file in file_list:
        # do_stuff_with_the_file
        counter += 1
        percent = 100 * counter / len(file_list)
        print percent
</code></pre>

<p>Make the <code>process_files</code> function a generator function that <em>yields</em> a value (the progress value) and pass it as a callback to a method in your <code>Window</code> class that updates the progress bar value. I have added a <code>time.sleep</code> call in your function so you can observe the progress:</p>

<pre><code>import time
from worker import process_files

class Window(QtGui.QMainWindow):
    def __init__(self):
        ...

    def observe_process(self, func=None):
        try:
            for prog in func():
                self.progress.setValue(prog)
        except TypeError:
            print('callback function must be a generator function that yields integer values')
            raise


app = QtGui.QApplication(sys.argv)
GUI = Window()
# process files and report progress using .setValue(percent)
GUI.observe_process(process_files)
sys.exit(app.exec_())
</code></pre>

<p><strong>worker.py</strong></p>

<pre><code>def process_files():
    file_list = ['file1', 'file2', 'file3']
    counter = 0
    for file in file_list:
        counter += 1
        percent = 100 * counter / len(file_list)
        time.sleep(1)
        yield percent
</code></pre>

<hr>

<p><strong>Result</strong>:</p>

<p>After processing <code>file2</code></p>

<p><a href="https://i.stack.imgur.com/10LSf.png" rel="nofollow"><img src="https://i.stack.imgur.com/10LSf.png" alt="enter image description here"></a></p>

python callback pyqt