使用 PyQt 连续显示下载百分比的方法?

Ways to show download percentage continuously using PyQt?

我写了一些从网上下载文件的代码。 下载时,它使用 PyQt 中的 QProgressBar 显示百分比。 但是下载的时候就停了,最后只显示100%。 我应该怎么做才能连续显示百分比?

这是python代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, urllib2
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import uic
form_class = uic.loadUiType("downloadergui.ui")[0]

class MainWindow(QMainWindow, form_class):
    def __init__(self):
        super(MainWindow, self).__init__() 
        self.setupUi(self)

        self.connect(self.downloadButton, SIGNAL("clicked()"), self.downloader)

    def downloader(self):
        print "download"
        url = "[[Fill in the blank]]"
        file_name = url.split('/')[-1]
        u = urllib2.urlopen(url)
        f = open(file_name, 'wb')
        meta = u.info()
        file_size = int(meta.getheaders("Content-Length")[0])
        self.statusbar.showMessage("Downloading: %s Bytes: %s" % (file_name, file_size))


        file_size_dl = 0
        block_sz = 8192
        while True:
            buffer = u.read(block_sz)
            if not buffer:
                break
            file_size_dl += len(buffer)
            f.write(buffer)
            downloadPercent = int(file_size_dl * 100 / file_size)
            self.downloadProgress.setValue(downloadPercent)
        f.close()
        pass

app = QApplication(sys.argv)
myWindow = MainWindow()
myWindow.show()
app.exec_()

GUI 始终作为 event-driven 模型工作,这意味着它的工作取决于从内部和外部接收事件。

例如,当你给它设置值时,它会发出一个值改变的信号。在您的情况下,您的下载逻辑设置了进度条的值。但是程序处理程序没有机会更新 UI 因为你的下载逻辑持有主线程。

这就是为什么我们说您不能在 UI 主线程中执行 long-time-consume 逻辑。

在你的情况下,我建议你使用新线程通过向主线程发出信号来下载和更新进度值。