在for循环中更新PyQt4进度条 - Python 2.7

时间:2016-11-04 22:49:12

标签: python python-2.7 progress-bar pyqt4

我扩充this example以允许我的用户在For循环中处理RAM密集型和迭代过程时知道程序所处的过程的哪个部分。我发现以下脚本只是要求打印计数值并等待几秒钟,但它不适用于更密集的功能。

# from https://pythonspot.com/en/qt4-progressbar/

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT
import time

class QProgBar(QProgressBar):

    value = 0

    @pyqtSlot()
    def increaseValue(progressBar):
        progressBar.setValue(progressBar.value)
        progressBar.value = progressBar.value+1

# Create an PyQT4 application object.
a = QApplication(sys.argv)       

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window title  
w.setWindowTitle("PyQT4 Progressbar @ pythonspot.com ") 

# Create progressBar. 
bar = QProgBar(w)
bar.resize(320,50)    
bar.setValue(0)


bar.setAlignment(Qt.AlignCenter)
bar.move(0,50)

label = QLabel("test",w)
label.setStyleSheet("QLabel { font-size: 20px }")
label.setAlignment(Qt.AlignCenter)
label.move(0,10)

# create timer for progressBar
'''timer = QTimer()
bar.connect(timer,SIGNAL("timeout()"),bar,SLOT("increaseValue()"))
timer.start(400)'''

# Show window
w.show()

for i in range(0,100):
    print(i) 
    ### Do action
    bar.setValue(i)
    time.sleep(0.5)

sys.exit(a.exec_())

我能做些什么来让这项工作更激烈的行动?有没有人知道我可以在for循环中轻松插入进度条的更好的包?

我是GUI开发的新手,我真的只需要简单的UI。

提前感谢您提供的任何帮助:)

1 个答案:

答案 0 :(得分:1)

在您将控制权交还给事件循环之前,Qt不会更新您的UI,也就是说,直到您的for循环结束。您可以通过调用processEvents来使事件循环更新UI:

for i in range(0,100):
    print(i) 
    ### Do action
    bar.setValue(i)
    a.processEvents()
    time.sleep(0.5)