如何顺利显示QProgressBar?

时间:2014-07-09 04:47:08

标签: qt pyqt pyside qprogressbar

我在MacOSX上学习Pyside QProgressBar。当我像下面这样使用QProgressBar时,它只表示0%或100%。如何顺利制作QProgressBar?有没有办法做到这一点?

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

2 个答案:

答案 0 :(得分:3)

摆脱这段代码:

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

而是添加一个全局变量p:

p = 0

并在drawBar()函数中增加它:

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

答案 1 :(得分:0)

QPropertyAnimation易于使用,它可以为您提供顺畅的更改。

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

编辑后的帖子:

只需用我建议的代码

替换pbar.show()和app.exec()之间的所有内容

以下是完整的代码:

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_()
相关问题