2016-01-12 50 views
0

我寫了一些從網上下載文件的代碼。 下載時,它顯示在PyQt中使用QProgressBar的百分比。 但是,當我下載時它會停止,最後只會在完成時顯示100%。 我該怎麼做才能持續顯示百分比?如何使用PyQt連續顯示下載百分比?

這裏的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_() 
+1

相關:http://stackoverflow.com/q/2482437/1994235和http://stackoverflow.com/q/30823863/1994235 –

回答

1

GUI總是可以作爲事件驅動的模型,這意味着它的工作原理依賴於從內部和外部接收事件。

例如,當你setValue它發出valuechange的信號。在你的情況下,你下載邏輯你設置進度條的價值。但程序處理程序沒有機會更新UI,因爲您的下載邏輯保存了主線程。

那爲什麼我們說你不能在主UI線程中做長時間消耗邏輯。

在你的情況下,我建議你使用一個新的線程下載並通過向主線發送信號來更新進度值。