說明
QProgressBar,進度條控件,使用很簡單。但如何結合下載下傳功能,實作下載下傳進度條呢?
本文主要參考了《
PyQt5實作下載下傳進度條》這篇文章,感謝作者的分享。
其中的下載下傳線程,基本原封不動的照搬了,這個下載下傳線程正是技術要點所在。
下載下傳線程
這個下載下傳線程,其實包含了不少知識點,可以多多借鑒參考哦。
1.pyqt5的線程 QThread
2.requests 流下載下傳模式
3.自定義信号和槽函數
【如下代碼,完全複制,直接運作,即可使用】
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import queue #如果不加載這個模闆,pyinstaller打包後,可能無法運作requests模闆
import requests
################################################
################################################
class Widget(QWidget):
def __init__(self, *args, **kwargs):
super(Widget, self).__init__(*args, **kwargs)
layout = QHBoxLayout(self)
# 增加進度條
self.progressBar = QProgressBar(self, minimumWidth=400)
self.progressBar.setValue(0)
layout.addWidget(self.progressBar)
# 增加下載下傳按鈕
self.pushButton = QPushButton(self, minimumWidth=100)
self.pushButton.setText("下載下傳")
layout.addWidget(self.pushButton)
# 綁定按鈕事件
self.pushButton.clicked.connect(self.on_pushButton_clicked)
# 下載下傳按鈕事件
def on_pushButton_clicked(self):
the_url = 'http://cdn2.ime.sogou.com/b24a8eb9f06d6bfc08c26f0670a1feca/5c9de72d/dl/index/1553820076/sogou_pinyin_93e.exe'
the_filesize = requests.get(the_url, stream=True).headers['Content-Length']
the_filepath ="D:/sogou_pinyin_93e.exe"
the_fileobj = open(the_filepath, 'wb')
#### 建立下載下傳線程
self.downloadThread = downloadThread(the_url, the_filesize, the_fileobj, buffer=10240)
self.downloadThread.download_proess_signal.connect(self.set_progressbar_value)
self.downloadThread.start()
# 設定進度條
def set_progressbar_value(self, value):
self.progressBar.setValue(value)
if value == 100:
QMessageBox.information(self, "提示", "下載下傳成功!")
return
##################################################################
#下載下傳線程
##################################################################
class downloadThread(QThread):
download_proess_signal = pyqtSignal(int) #建立信号
def __init__(self, url, filesize, fileobj, buffer):
super(downloadThread, self).__init__()
self.url = url
self.filesize = filesize
self.fileobj = fileobj
self.buffer = buffer
def run(self):
try:
rsp = requests.get(self.url, stream=True) #流下載下傳模式
offset = 0
for chunk in rsp.iter_content(chunk_size=self.buffer):
if not chunk: break
self.fileobj.seek(offset) #設定指針位置
self.fileobj.write(chunk) #寫入檔案
offset = offset + len(chunk)
proess = offset / int(self.filesize) * 100
self.download_proess_signal.emit(int(proess)) #發送信号
#######################################################################
self.fileobj.close() #關閉檔案
self.exit(0) #關閉線程
except Exception as e:
print(e)
####################################
#程式入口
####################################
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
本文如有幫助,敬請留言鼓勵。
本文如有錯誤,敬請留言改進。