Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

python - Report progress to QProgressBar using variable from an imported module

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...