带有进度条的 PyQt4 崩溃

PyQt4 crash with progress bar

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

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

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

这是进度条:

我不会尝试通过在循环中调用 show 来更新 UI,而是调用 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 在它自己的线程中实现您的下载过程,并使用信号和槽结构将进度传递给您的进度条。如果您需要,我可以为您提供示例。