PyQt5 – How to automate Progress Bar while downloading using urllib?
PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps.
In this article, we will learn how to automate the Progress Bar in PyQt5. By automating what we mean is to dynamically change and set the value of progress bar. Suppose, you are downloading any file over the internet and want to show the progress of the download, then this article will surely help you.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
In the present example, we are using the Urllib library to download the files as its the most common library to download files using python.
self.progressBar = QProgressBar(self)
QProgressBar class is for creating the progress bar object.
Firstly, go through the following code, then we will explain what the whole thing does.
Below is the syntax for urllib, we have to study all the parameters it takes.
Syntax: urllib.request.urlretrieve(url, filename, reporthook)
Parameters: This method will take following parameters :
The first parameter is the url of the file, which is to be downloaded.
The second parameter, if present, specifies the file location to save the file (if this argument is not passed, the location will be a temp file with an auto-generated name).
The third parameter is a callable that will be called when the file is being downloaded and once after another, each block would be read. The callable (which is a function Handle_Progress in this case) will be passed as three arguments :
- a count of blocks transferred so far (blocknum)
- block size in bytes (blocksize)
- the total size of the file (totalsize)
The function Handle_Progress hence receives three arguments. The current downloaded size of the file is calculated dynamically by multiplying blocknum and blocksize and is stored in the variable readed_data.
The rest of the work is done by the formula for calculating the percentage. We multiply readed_data by 100 and divide it by the total size of the file. It gives us the current download percentage. Then we set this download percentage to the progress bar using setValue() method of progressBar object.