pyqt5实现wget下载视频文件的进度条显示

简介:

最近在写一个项目,用到了wget下载视频,为了更好的视觉效果,所以使用pyqt5中QProgressBar来实现下载进度条。当视频开始下载就会弹出下载进度条,下载完成后进度条消失。效果如下图;

具体代码实现 :

import os
import sys
import wget
from PyQt5 import QtWidgets
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QProgressBar, QHBoxLayout, QWidget
from config.path import parent_path
from PyQt5.QtCore import QThread, pyqtSignal


class DownloadWidget(QWidget):
    def __init__(self, video_url, video_name):
        super(DownloadWidget, self).__init__()
        self.url = video_url
        self.target_name = video_name
        self.setWindowTitle('视频下载中...')
        layout = QHBoxLayout(self)

        # 创建进度条
        self.progressBar = QProgressBar(self, minimumWidth=400)
        self.progressBar.setStyleSheet("QProgressBar { border: 2px solid grey; border-radius: 5px; background-color: "
                                       "#FFFFFF; text-align: center;}QProgressBar::chunk {background:QLinearGradient("
                                       "x1:0,y1:0,x2:2,y2:0,stop:0 #666699,stop:1  #DB7093); }")
        font = QFont()
        font.setBold(True)
        font.setWeight(30)
        self.progressBar.setFont(font)

        self.progressBar.setValue(0)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setFormat('Loaded  %p%'.format(self.progressBar.value() - self.progressBar.minimum()))

        layout.addWidget(self.progressBar)

        # 创建并启动下载线程
        self.download_thread = DownloadThread(self.url, self.target_name)
        self.download_thread.progressChanged.connect(self.update_progress)
        self.download_thread.start()

    # 更新进度条
    def update_progress(self, value):
        if value == 100:
            print('下载完成!!!!!!')
            self.close()
        self.progressBar.setValue(value)


class DownloadThread(QThread):
    # 定义信号
    progressChanged = pyqtSignal(int)

    def __init__(self, video_url, video_name):
        super(DownloadThread, self).__init__()
        self.url = video_url
        self.target_name = video_name

    def run(self):
        tmpdir = parent_path + '\\static\\mp4'
        self.download_video(self.url, os.path.join(tmpdir, self.target_name))

    # 下载视频
    def download_video(self, url, target_path):
        wget.download(url, out=target_path, bar=self.progress_bar_callback)
        self.progressChanged.emit(100)

    # 回调函数,用于更新进度条
    def progress_bar_callback(self, current, total, width=80):
        progress = current / total * 100
        self.progressChanged.emit(int(progress))


if __name__ == '__main__':
    print("system open")
    app = QtWidgets.QApplication(sys.argv)
    main_ui = DownloadWidget("url", 'test.mp4')
    main_ui.show()
    sys.exit(app.exec_())

你可能感兴趣的:(Python,PyQt,Qt,qt,python,开发语言)