PyQt4崩溃与进度条

时间:2015-09-22 11:04:10

标签: python progress-bar pyqt4

我正在尝试进行具有自动进度的进度条的下载操作。

当我运行此代码时,进度条工作正常,但当我在表单中单击鼠标时程序停止工作。

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import urllib

app = QApplication(sys.argv)
app.setStyle('Cleanlooks')
label = QLabel()
progressx = QProgressBar(label)

url = "http://l3cdn.riotgames.com/ShellInstaller/EUNE/LeagueofLegends_EUNE_Installer_9_15_2014.exe"
name = url.split('/')[-1]
def report(count, blockSize, totalSize):
        global percent
        percent = int(count*blockSize*100/totalSize)

        sys.stdout.write("\r%d%%" % percent + ' complete')
        progressx.setValue(percent)
        label.show()

urllib.urlretrieve(url, name, reporthook=report)
sys.exit(app.exec_())

这是进度条:

Broken progress bar

1 个答案:

答案 0 :(得分:2)

我可以通过在循环中调用show来尝试更新您的用户界面,而是拨打QtGui.QApplication.processEvents()来代替:

import sys
from PyQt4 import QtGui
import urllib

app = QtGui.QApplication(sys.argv)
app.setStyle('Cleanlooks')

progressx = QtGui.QProgressBar()
progressx.show()

url = "http://l3cdn.riotgames.com/ShellInstaller/EUNE/LeagueofLegends_EUNE_Installer_9_15_2014.exe"
name = url.split('/')[-1]
def report(count, blockSize, totalSize):
    global percent
    percent = int(count*blockSize*100/totalSize)

    sys.stdout.write("\r%d%%" % percent + ' complete')
    progressx.setValue(percent)

    QtGui.QApplication.processEvents()

urllib.urlretrieve(url, name, reporthook=report)
sys.exit(app.exec_())

或者,如果它仍然无法正常工作,您可以尝试使用QThread在自己的线程中实现下载过程,并使用信号和插槽结构将进度传递到进度条。如果需要,我可以为您提供一个示例。