PyQt Progressbar QThread无法正常工作

时间:2014-03-10 04:04:20

标签: python pyqt progress-bar qthread qtcore

我的代码有问题。我的计划是使用进度条显示for循环的进度。我的想法是使用Qthread。我的代码以某种方式工作,但不是100%正确。进度条显示for循环的进度,但不是通过线程,即如果我尝试单击多次,则停止GUI冻结。 我不是QtCore专家。可以请某人帮助我并告诉我为什么它不能按我想要的方式工作?

非常感谢!

from PyQt4 import QtGui, QtCore

#Progressbar
class MyCustomWidget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(MyCustomWidget, self).__init__(parent)
        layout = QtGui.QVBoxLayout(self)       

        self.progressBar = QtGui.QProgressBar(self)
        self.progressBar.setRange(0,100)
        layout.addWidget(self.progressBar)

    #Update Progressbar
    def onProgress(self, i):
        self.progressBar.setValue(i)
        if self.progressBar.value() >= self.progressBar.maximum():
            self.close()

#Threading Class
class ASA(QtCore.QThread):
    notifyProgress = QtCore.pyqtSignal(int)
    def run(self, i):

        #Sends the new information to the Update Function
        self.notifyProgress.emit(i)
        time.sleep(0.01)

#-----------------------------------------#
#Main Function
app = QtGui.QApplication(sys.argv)
bar = MyCustomWidget()
bar.show()

bar.asa = ASA()
bar.asa.notifyProgress.connect(bar.onProgress)
bar.asa.start()

#For loop for the progressbar
for i in range(105):
    ASA.run(bar.asa, i)
    time.sleep(0.5)  

sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:2)

循环需要在线程本身内运行:

def run(self):
    #Sends the new information to the Update Function
    for i in range(105):
        self.notifyProgress.emit(i)
        time.sleep(0.01)