Last active
October 27, 2022 08:34
-
-
Save StephenNneji/124000984d88af9d209b509b56aa7bd2 to your computer and use it in GitHub Desktop.
Singleton progress bar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This is a demo of updating progress using a singleton class. This allow each class to | |
report its own progress without changing the argument list so that all functions recieve | |
a progrees object. | |
""" | |
from threading import Thread | |
import time | |
import sys | |
from PyQt5 import QtCore, QtWidgets | |
class Singleton(type(QtCore.QObject), type): | |
"""Metaclass used to create a PyQt singleton""" | |
def __init__(cls, name, bases, cls_dict): | |
super().__init__(name, bases, cls_dict) | |
cls._instance = None | |
def __call__(cls, *args, **kwargs): | |
if cls._instance is None: | |
cls._instance = super().__call__(*args, **kwargs) | |
return cls._instance | |
class ProgressReport(QtCore.QObject, metaclass=Singleton): | |
"""Create singleton class to update progress bar""" | |
progress_updated = QtCore.pyqtSignal(int) | |
def __init__(self): | |
super().__init__() | |
self.percentage = 0 | |
def updateProgress(self, progress): | |
self.percentage += progress | |
self.progress_updated.emit(self.percentage) | |
def another_function(): | |
report = ProgressReport() | |
report.percentage = 0 # will do better than this | |
for _ in range(100): | |
time.sleep(0.1) | |
report.updateProgress(1) | |
def first_function(): | |
report = ProgressReport() | |
report.percentage = 0 # will do better than this | |
for _ in range(100): | |
time.sleep(0.1) | |
report.updateProgress(1) | |
class Window(QtWidgets.QWidget): | |
def __init__(self): | |
super().__init__() | |
self.title = 'Simple Example' | |
self.resize(250, 100) | |
layout = QtWidgets.QVBoxLayout() | |
self.setLayout(layout) | |
button1 = QtWidgets.QPushButton('First') | |
button1.clicked.connect(lambda: self.buttonClicked(1)) | |
layout.addWidget(button1) | |
button2 = QtWidgets.QPushButton('Second') | |
button2.clicked.connect(lambda: self.buttonClicked(2)) | |
layout.addWidget(button2) | |
report = ProgressReport() | |
self.dialog = QtWidgets.QProgressDialog('Progress', 'Cancel', 0, 100, self) | |
self.dialog.cancel() | |
report.progress_updated.connect(self.dialog.setValue) | |
def buttonClicked(self, index): | |
task = first_function if index==1 else another_function | |
thread = Thread(target=task) | |
thread.start() | |
self.dialog.show() | |
if __name__ == '__main__': | |
app = QtWidgets.QApplication([]) | |
window = Window() | |
window.show() | |
sys.exit(app.exec()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment