Search code examples
qtpyqtpysideqprogressbar

How to show QProgressBar smoothly?


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

Solution

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