0

I wrote some code that download file from web. While downloading, it shows the percentage using QProgressBar in PyQt. But it stops when I downloading, and finally only shows 100% when it done. What should I do to show percentage continuously?

Here's the python code

#!/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_()
Lee M.U.
  • 123
  • 1
  • 12

1 Answers1

1

GUI always works as event-driven model, which means it works depend on receiving event from inside and outside.

For example, when u setValue to it emit a signal of valuechange. In ur case, ur downloading logic u set the progressbar's value. But the program handler dont have chance to update the UI because ur download logic hold the main thread.

That why we say u can't do the long-time-consume logic in the main UI thread.

In ur case, i suggested u use a new thread to download and update the progress value through emitting a signal to the main thread.

herokingsley
  • 403
  • 3
  • 10