I'm trying to show QProgressBar updates smoothly. The below code is filling up the progress bar from 0 to 100 triggered from a QThread, but I want to show the incremental progress update smoothly. Is there any way to do this?
import time
from PySide2.QtWidgets import QProgressBar, QApplication
from PySide2.QtCore import Slot, QThread, Signal, QObject
class ProgressBarUpdater(QThread):
progressBarValue = Signal(int)
def run(self):
value: int = 0
while value <= 100:
time.sleep(0.1)
self.progressBarValue.emit(value)
value = 5
def main():
app = QApplication([])
pbar = QProgressBar()
pbar.setMinimum(0)
pbar.setMaximum(100)
pbar.show()
@Slot(int)
def progressbar_update(value: int):
pbar.setValue(value)
progressBarUpdater = ProgressBarUpdater()
progressBarUpdater.progressBarValue.connect(progressbar_update)
progressBarUpdater.start()
app.exec_()
if __name__ == "__main__":
main()
CodePudding user response:
You can use a QPropertyAnimation to update the values:
import time
from PySide2.QtCore import QPropertyAnimation, QThread, Signal
from PySide2.QtWidgets import QProgressBar, QApplication
class ProgressBarUpdater(QThread):
progressBarValue = Signal(int)
def run(self):
value: int = 0
while value <= 100:
time.sleep(0.1)
self.progressBarValue.emit(value)
value = 5
class ProgressBar(QProgressBar):
def update_value(self, value, animated=True):
if animated:
if hasattr(self, "animation"):
self.animation.stop()
else:
self.animation = QPropertyAnimation(
targetObject=self, propertyName=b"value"
)
self.animation.setDuration(100)
self.animation.setStartValue(self.value())
self.animation.setEndValue(value)
self.animation.start()
else:
self.setValue(value)
def main():
app = QApplication([])
pbar = ProgressBar()
pbar.setMinimum(0)
pbar.setMaximum(100)
pbar.show()
progressBarUpdater = ProgressBarUpdater()
progressBarUpdater.progressBarValue.connect(pbar.update_value)
progressBarUpdater.start()
app.exec_()
if __name__ == "__main__":
main()