How to show QProgressBar smoothly?

2019-08-09 03:08发布

问题:

I'm learning Pyside QProgressBar on MacOSX. When I use QProgressBar like following, it only indicate 0% or 100%. How to make a QProgressBar smoothly? Is there any way to do this?

from PySide.QtGui import QApplication, QProgressBar, QWidget
from PySide.QtCore import QTimer
import time

app = QApplication([])
pbar = QProgressBar()
pbar.setMinimum(0)
pbar.setMaximum(100)

pbar.show()

def drawBar():
    global pbar
    pbar.update()

t = QTimer()
t.timeout.connect(drawBar)
t.start(100)

for i in range(1,101):
    time.sleep(0.1)
    pbar.setValue(i)

app.exec_()

回答1:

Get rid of this code:

for i in range(1,101):   # this won't work, because
    time.sleep(0.1)      # Qt's event loop can't run while
    pbar.setValue(i)     # you are forcing the thread to sleep

and instead, add a global variable p:

p = 0

and increment it in your drawBar() function:

def drawBar():
    global pbar
    global p
    p = p + 1
    pbar.setValue(p)
    pbar.update()


回答2:

QPropertyAnimation is easy to use and it does the smooth change for you.

    animation = QtCore.QPropertyAnimation(pbar, "value")
    animation.setDuration(???)
    animation.setStartValue(0)
    animation.setEndValue(100)
    animation.start()

Edited post:

Just replace everything between pbar.show() and app.exec() by the code I suggested

Here is the complete code:

from PyQt5.QtWidgets import QWidget, QProgressBar, QApplication
from PyQt5.QtCore import QTimer, QPropertyAnimation

app = QApplication([])
pbar = QProgressBar()
pbar.setMinimum(0)
pbar.setMaximum(100)

pbar.show()

animation = QPropertyAnimation(pbar, "value")
animation.setDuration(2000)
animation.setStartValue(0)
animation.setEndValue(100)
animation.start()

app.exec_()