Report progress to QProgressBar using variable fro

2019-02-28 03:57发布

I have a PyQT GUI application progress_bar.pywith a single progressbar and an external module worker.py with a process_files() function which does some routine with a list of files and reports current progress using percent variable.

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

Here are my modules:

progress_bar.py

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_())

worker.py

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

1条回答
Root(大扎)
2楼-- · 2019-02-28 04:33

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

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_())

worker.py

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

Result:

After processing file2

enter image description here

查看更多
登录 后发表回答