PyQT5: Worker thread's progress bar only updates after main thread's progress bar has updated

19 views Asked by At

This is a simplified code from one of my projects, I'm trying to update one progressbar from inside main thread and another from a worker thread. In actual project, main progress bar represents directory being scanned, and worker thread extracts data from certain files and saves to database.

I can not seem to figure out a way that these two progressbars function independent of each other. Worker progressbar only starts mving when main has reached 100%

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QProgressBar
from PyQt5.QtCore import QObject, pyqtSignal, QThread, QTimer
import time

class Worker(QObject):
    progressChanged = pyqtSignal(int)

    def __init__(self):
        super().__init__()

    def repeat_process_decoded_instances(self):
        counter = 0
        total_counts = 100

        while counter < total_counts:
            counter += 0.5
            percentage = round(counter / total_counts * 100)
            self.progressChanged.emit(percentage)
            time.sleep(0.1)

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.worker = Worker()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        self.progress_label1 = QLabel("Main Thread Progress:")
        self.progress_bar1 = QProgressBar()
        layout.addWidget(self.progress_label1)
        layout.addWidget(self.progress_bar1)

        self.progress_label2 = QLabel("Worker Thread Progress:")
        self.progress_bar2 = QProgressBar()
        layout.addWidget(self.progress_label2)
        layout.addWidget(self.progress_bar2)

        self.setLayout(layout)
        self.setWindowTitle("Dual Progress Bars App")
        self.show()

        self.worker.progressChanged.connect(self.updateProgressBar2)

        self.worker_thread = QThread()
        self.worker.moveToThread(self.worker_thread)
        self.worker_thread.start()
        QTimer.singleShot(0, self.worker.repeat_process_decoded_instances)

    def updateProgressBar2(self, percentage):
        self.progress_bar2.setValue(int(percentage))

def main():
    app = QApplication(sys.argv)
    window = MyWindow()
    
    count = 0
    total_counts = 100
    while count < total_counts:
        count += 2
        percentage = round(count / total_counts * 100)
        window.progress_bar1.setValue(percentage)
        time.sleep(0.1)
        
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

0

There are 0 answers