如何使用 PySide2 的 QPropertyAnimation 平滑地显示 QProgressBar 值更新?

How to show QProgressBar value updates smoothly using QPropertyAnimation of PySide2?

我正在努力显示 QProgressBar 更新顺利。下面的代码填充了由 QThread 触发的从 0 到 100 的进度条,但我想顺利地显示增量进度更新。有什么办法吗?

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()

您可以使用 QPropertyAnimation 来更新值:

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()