Report progress to QProgressBar using variable from an imported module

前端 未结 1 1781
别那么骄傲
别那么骄傲 2021-01-25 13:41

I have a PyQT GUI application progress_bar.pywith a single progressbar and an external module worker.py with a process_files() function wh

相关标签:
1条回答
  • 2021-01-25 14:09

    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

    0 讨论(0)
提交回复
热议问题