본문 바로가기
Qt5 Python GUI Programming Cookbook

Event Handling - Signals andSlots

by 자동매매 2023. 2. 27.

In this chapter, we will learn about the following topics:

  • Using Signal/Slot Editor
  • Copying and pasting text from one Line Edit widget to another
  • Converting data types and making a small calculator
  • Using the Spin Box widget
  • Using scrollbars and sliders
  • Using List Widget
  • Selecting multiple list items from one List Widget and displaying them in another
  • Adding items into List Widget
  • Performing operations in List Widget Using the Combo Box widget Using the Font Combo Box widget Using the Progress Bar widget

Introduction

Event handling is an important mechanism in every application. The application should not only recognize the event, but must take the respective action to serve the event, too. The action taken on any event determines the course of the application. Each programming language has a different technique for handling or listening to events. Let's see how Python handles its events.

Using Signal/Slot Editor

In PyQt, the event handling mechanism is also known as signals and slots. An event can be in the form of clicking or double-clicking on a widget, or pressing the Enter key, or selecting an option from a radio button, checkbox, and so on. Every widget emits a signal when any event is applied on it and, that signal needs to be connected to a method, also known as a slot. A slot refers to the method containing the code that you want to be executed on the occurrence of a signal. Most widgets have predefined slots; you don't have to write code to connect a predefined signal to a predefined slot.

You can even edit a signal/slot by navigating to the Edit | Edit Signals/Slots tool in the toolbar.

How to do it...

To edit the signals and slots of different widgets placed on the form, you need to switch to signals and slots editing mode by performing the following steps:

  1. You can press the F4 key, navigate to the Edit | Edit Signals/Slots option, or select the Edit Signals/Slots icon from the toolbar. The mode displays all the signal and slot connections in the form of arrows, indicating the connection of a widget with its respective slot.
  • You can also create new signal and slot connections between widgets in this mode and delete an existing signal.
  1. To establish a signal and slot connection between two widgets in a form, select a widget by left-clicking the mouse on the widget, dragging the mouse towards another widget to which you want to connect, and releasing the mouse button over it.
  2. To cancel the connection while dragging the mouse, simply press the Esc key.
  3. On releasing the mouse over the destination widget, a Connection Dialog box appears, prompting you to select a signal from the source widget and a slot from the destination widget.
  4. After selecting the respective signal and slot, select OK to establish the signal and slot connection.
    The following screenshot shows dragging a Push Button over a Line Edit widget:

On releasing the mouse button on the Line Edit widget, you get the list of predefined signals and slots, as shown in the following screenshot:

  1. When connected, the selected signal and slot will appear as labels in the arrow, connecting the two widgets.
  2. To modify a signal and slot connection, double-click the connection path or one of its labels to display the Configure Connection dialog box.
  3. From the Configure Connection dialog, you can edit a signal or a slot as desired.
  4. To delete a signal and slot connection, select its arrow on the form and press the Delete key.

The signal and slot connection can also be established between any widget and the form. To do so, you can perform the following steps:

  1. Select the widget, drag the mouse, and release the mouse button over the form. The end point of the connection changes to the electrical ground symbol, representing that a connection has been established with the form.
  2. To come out of signal and slot editing mode, navigate to Edit | Edit Widgets or press the F3 key.

Copying and pasting text from one Line Edit widget to another

This recipe will make you understand how an event performed on one widget invokes a predefined action on the associated widget. Because we want to copy content from one Line Edit widget on clicking the push button, we need to invoke the selectAll() method on the occurrence of the pressed() event on push button. Also, we need to invoke the copy() method on occurrence of the released() event on the push button. To paste the content in the clipboard into another Line Edit widget on clicking of another push button, we need to invoke the paste() method on the occurrence of the clicked() event on another push button.

demoSignalSlot1.py
0.00MB
demoSignalSlot1.ui
0.00MB

 

 

 

Getting ready

Let's create an application that consists of two Line Edit and two Push Button widgets. On clicking the first push button, the text in the first Line Edit widget will be copied and on clicking the second push button, the text copied from the first Line Edit widget will be pasted onto the second Line Edit widget.

Let's create a new application based on the Dialog without Buttons template by performing the following steps:

  1. Begin by adding QLineEdit and QPushButton to the form by dragging and dropping the Line Edit and Push Button widgets from the Widget box on the form.
  2. [참조] To preview a form while editing, select either Form, Preview, or use Ctrl + R .
  3. To copy the text of the Line Edit widget when the user selects the push button on the form, you need to connect the push button's signal to the slot of Line Edit. Let's learn how to do it.

How to do it...

Initially, the form is in widget editing mode, and to apply signal and slot connections, you need to first switch to signals and slots editing mode:

  1. Select the Edit Signals/Slots icon from the toolbar to switch to signals and slots editing mode.
  2. On the form, select the push button, drag the mouse to the Line Edit widget, and release the mouse button. The Configure Connection dialog will pop up, allowing you to establish a signal and slot connection between the Push Button and the Line Edit widgets, as shown in the following screenshot:
  3. Select the pressed() event or signal from the pushButton (QPushButton) tab and the selectAll() slot for the lineEdit (QLineEdit) tab.The connected signal of the Push Button widget with the slot of Line Edit will appear in the form of an arrow, representing the signal and slot connection between the two widgets, as shown in the following screenshot:

  1. Set the text property of the Push Button widget to Copy to represent the fact that it will copy the text entered in the Line Edit widget.
  2. Next, we will repeat the procedure of clicking the push button and dragging it to the Line Edit widget to connect the released() signal of the push button with the copy() slot of the Line Edit widget. On the form, you will see another arrow, representing the second signal and slot connection established between the two widgets, as is shown in the following screenshot:

  1. In order to paste the copied content, drag and drop one push button and one Line Edit widget on the form.
  2. Set the text property of the Push Button widget to Paste.
  3. Click the push button and, keeping the mouse button pressed, drag it and release it on the Line Edit widget.
  4. From the Configure Connection dialog, select the clicked() event from the pushButton (QPushButton) column and the paste() slot from the lineEdit (QLineEdit) column.
  5. Save the form with the name demoSignal1.ui. The form will now appear as shown in the following screenshot:

The form will be saved in a file with the .ui extension. The demoSignal1.ui file will contain all the information of the form, its widgets, layout, and so on. The .ui file is an XML file, and it needs to be converted into Python code by making use of the pyuic5 utility. The generated Python code file, demoSignal1.py, can be seen in the source code bundle of this book. In the demoSignal1.py file, you will find that it imports everything from both modules, QtCore and QtGui, as you will be needing them for developing GUI applications:

  • QtCore: The QtCore module forms the foundation of all Qt-based applications. It contains the most fundamental classes, such as QCoreApplication, QObject, and so on. These classes do important tasks, such as event handling, implementing the signal and slot mechanism, I/O operations, handling strings, and so on. The module includes several classes, including QFile, QDir, QIODevice, QTimer, QString, QDate, and QTime.
  • QtGui: As the name suggests, the QtGUI module contains the classes required in developing cross-platform GUI applications. The module contains the GUI classes, such as QCheckBox, QComboBox, QDateTimeEdit, QLineEdit, QPushButton, QPainter, QPaintDevice, QApplication, QTextEdit, and QTextDocument.
  • Treat the demoSignalSlot1.py file, as a header file and import it to the file from which you will invoke its user interface design.
  • Create another Python file with the name calldemoSignal1.pyw and import the demoSignal1.py code into it:
    import sys
import sys
from PyQt5.QtWidgets import QDialog, QApplication
from demoSignalSlot1 import *

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

if __name__=="__main__":
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

 

How it works...

The sys module is imported as it supplies access to the command-line arguments stored in the sys.argv list. This is because every PyQt GUI application must have a QApplication object to provide access to information such as the application's directory, screen size, and so on, so that you create an QApplication object. To enable PyQt to use and apply command-line arguments (if any), you pass the command-line arguments while creating a QApplication object. You create an instance of MyForm and call its show() method, which adds a new event to the QApplication object's event queue. This new event is used to display all the widgets specified in the MyForm class. The app.exec_ method is called to start the QApplication object's event loop. Once the event loop begins, the top-level widget used in the class, MyForm, is displayed, along with its child widgets. All the system- generated events, as well as user interaction events, are added to the event queue. The application's event loop continuously checks to see whether an event has occurred. On the occurrence of an event, the event loop processes it and invokes the associated slot or method. On closing the top-level widget of the application, PyQt deletes the widget and performs a clean termination of the application.

In PyQt, any widget can be used as a top-level window. The super().__init__() method invokes the base class constructor from the MyForm class, that is, the constructor of the QDialog class is invoked from MyForm class to indicate that QDialog is displayed through this class is a top-level window.

The user interface design is instantiated by calling the setupUI() method of the class that was created in the Python code (Ui_Dialog). We create an instance of the Ui_Dialog class, the class that was created in the Python code, and invoke its

setupUi() method. The Dialog widget will be created as the parent of all the user interface widgets and displayed on the screen. Remember, QDialog, QMainWindow, and all of the PyQt's widgets are derived from QWidget.

On running the application, you get two pairs of the Line Edit and Push Button widgets. On typing text into one Line Edit widget, when you click the Copy push button, the text will be copied.

Now, on clicking the Paste push button, the copied text will be pasted in the second Line Edit widget, as shown in the following screenshot:

Converting data types and making a small calculator

The most commonly used widget for accepting one-line data is the Line Edit widget, and the default data type in a Line Edit widget is string. In order to do any computation on two integer values, you need to convert the string data entered in the Line Edit widget to the integer data type and then convert the result of computation, which will be a numeric data type, back to string type before being displaying through a Label widget. This recipe does exactly that.

demoCalculator.py
0.00MB
demoCalculator.ui
0.00MB

 

 

 

How to do it...

To understand how data is accepted by the user and how type casting is done, let's create an application based on the Dialog without Buttons template by performing the following steps:

Add three QLabel, two QLineEdit, and one QPushButton widget to the form by dragging and dropping three Label, two Line Edit, and four Push Button widgets on the form.
Set the text property of the two Label widgets to Enter First Number and Enter Second Number.
Set the objectName property of the three Labels to labelFirstNumber, labelSecondNumber, and labelResult.
Set the objectName property of the two Line Edit widgets to lineEditFirstNumber and lineEditSecondNumber.
Set the objectName property of the four Push Button widgets to pushButtonPlus, pushButtonSubtract, pushButtonMultiply, and pushButtonDivide, respectively.

Set the push button's text property to +, -, x, and /, respectively.
Delete the default text property of the third label, because the Python script will set the value and then display it when the two numerical values are added.
Don't forget to drag the Label widget in the designer in order to ensure it is long enough to display the text that will be assigned to it through the Python script.
Save the UI file as demoCalculator.ui.
You can also increase the width of the Label widget by setting the width property under geometry from the Property Editor window:

The .ui file, which is in XML format, needs to be converted into Python code. The generated Python code, demoCalculator.py, can be seen in the source code bundle of this book.

Create a Python script named callCalculator.pyw that imports the Python code demoCalculator.py to invoke a user interface design, and that fetches the values entered in the Line Edit widgets and displays their addition. The code in the Python script callCalculator.pyw is shown here:

test.py
0.00MB

 

 

 

How it works...

There are the following four functions used in this code:

  • len(): This function returns the number of characters in the string
  • str(): This function converts the argument passed into the string data type
  • int(): This function converts the argument passed into the integer data type
  • round(): This function rounds the number passed to the specified decimal digits

The clicked() event of pushButtonPlus is connected to the addtwonum() method to display the sum of the numbers entered in the two Line Edit widgets. In the addtwonum() method, you first validate lineEditFirstNumber and lineEditSecondNumber to ensure that if either Line Edit is left blank by the user, the value of that Line Edit is zero.

The values entered in the two Line Edit widgets are retrieved, converted into integers through int(), and assigned to the two variables a and b. The sum of the values in the a and b variables is computed and stored in the sum variable. The result in the variable sum is converted into string format through str method and displayed via labelResult, as shown in the following screenshot:

Similarly, the clicked() event of pushButtonSubtract is connected to the subtracttwonum() method to display the subtraction of the numbers entered in the two Line Edit widgets. Again, after validation of the two Line Edit widgets, the values entered in them are retrieved and converted into integers. Subtraction is applied on the two numbers and the result is assigned to the diff variable. Finally, the result in the diff variable is converted into string format through the str() method and displayed via labelResult, as shown in the following screenshot:

Similarly, the clicked() event of pushButtonMultiply and pushButtonDivide are connected to the multiplytwonum() and dividetwonum() methods, respectively. These methods multiply and divide the values entered in the two Line Edit widgets and display them through the labelResult widget.

The result of the multiplication is shown in the following screenshot:

Using the Spin Box widget

The Spin Box widget is used for displaying integer values, floating-point values, and text. It applies a constraint on the user: the user cannot enter any random data, but can select only from the available options displayed through Spin Box. A Spin Box widget displays an initial value by default that can be increased or decreased by selecting the up/down button or up/down arrow key on the keyboard. You can choose a value that is displayed by either clicking on it or typing it in manually.

 

Getting ready

A Spin Box widget can be created using two classes, QSpinBox and QDoubleSpinBox, where QSpinBox displays only integer values, and the QDoubleSpinBox class displays floating-point values. Methods provided by QSpinBox are shown in the following list:

  • value(): This method returns the current integer value selected from the spin box.
  • text(): This method returns the text displayed by the spin box.
  • setPrefix(): This method assigns the prefix text that is prepended to the value returned by the spin box.
  • setSuffix(): This method assigns the suffix text that is to be appended to the value returned by the spin box.
  • cleanText(): This method returns the value of the spin box without a suffix, a prefix, or leading or trailing whitespaces.
  • setValue(): This method assigns the value to the spin box.
  • setSingleStep(): This method sets the step size of the spin box. Step size is the increment/decrement value of the spin box, that is, it is the value by which the spin box's value will increase or decrease on selecting the up or down buttons.
  • setMinimum(): This method sets the minimum value of the spin box.
  • setMaximum(): This method sets the maximum value of the spin box. setWrapping(): This method passes the Boolean value true to this method to enable wrapping in the spin box. Wrapping means the spin box returns to the first value (minimum value) when the up button is pressed while displaying the maximum value.

Signals emitted by the QSpinBox class are as follows:

  • valueChanged(): This signal is emitted when the value of the spin box is changed either by selecting the up/down button or using the setValue() method
  • editingFinished(): This signal is emitted when focus is lost on the spin box

The class used for dealing with float values in spin boxes is QDoubleSpinBox. All the preceding methods are supported by the QDoubleSpinBox class too. It displays values up to two decimal places by default. To change the precision, use round(), which displays the values up to the specified number of decimal places; the value will be rounded to the specified number of decimals.

Let's create an application that will ask the user to enter a price for a book, followed by the quantity of the books purchased by the customer, and will display the total amount of books. Also, the application will prompt you to enter a price for 1 kg of sugar, followed by the quantity of sugar bought by the user. On entering the quantity of sugar, the app will display the total amount of sugar. The quantity of the books and the sugar will be entered through a spin box and double spin box, respectively.

calldemoSpinner.pyw
0.00MB
demoSpinBox.py
0.00MB
demoSpinBox.ui
0.00MB

 

 

 

How to do it...

To understand how integer and float values can be accepted through spin boxes and used in further computation, let's create a new application based on the Dialog without Buttons template and follow these steps:

  1. Let's begin by dragging and dropping three Label, a Spin Box, a Double Spin Box, and four Line Edit widgets.
  2. The text property of two Label widgets is set to Book Price value and Sugar Price, and the objectName property of the third Label widget is set to labelTotalAmount.
  3. Set the objectName property of the four Line Edit widgets to lineEditBookPrice, lineEditBookAmount, lineEditSugarPrice, and lineEditSugarAmount, respectively.
  4. Set the objectName property of the Spin Box widget to spinBoxBookQty and that of the Double Spin Box widget to doubleSpinBoxSugarWeight.
  5. Delete the default text property of the third Label widget, TextLabel, as you will be setting its text in the program to display the total amount.
  6. The third Label widget will become invisible on deleting its text property.
  7. Disable the two Line Edit widgets, lineEditBookAmount and

lineEditSugarAmount, by unchecking their enabled property from the Property Editor window as you want them to display non-editable values.

  1. Save the application with the name demoSpinner.ui:
  2. On using the pyuic5 command utility, the .ui (XML) file will be converted into Python code. The generated Python code file, demoSpinner.py, can be seen in the source code of this book.
  3. Create a Python script file named calldemoSpinner.pyw that imports the code, demoSpinner.py, enabling you to invoke the user interface design that displays the numbers selected through spin boxes and also compute the total book amount and total sugar amount. The calldemoSpinner.pyw file will appear as shown here:

How it works...

In this code, you can see that the editingFinished** signal of the two spin boxes is

attached to the result1 and result2 functions. It means that when focus is lost on any of the spin boxes, the respective method will be invoked. Focus is lost on a widget when the user moves onto other widgets with the mouse or by pressing the Tab key:

In the result1 method, you retrieve the integer value for the purchased book quantity from the Spin Box widget and multiply it with the book price entered in the lineEditBookPrice widget to compute the total book cost. The total book cost is then displayed through the lineEditBookAmount widget.

Similarly, in the result2 method, you retrieve the floating-point value that is the weight of the sugar purchased from the double spin box and multiply it with the price of the sugar per kg entered in the lineEditSugarPrice widget to compute the total sugar cost, which is then displayed through the lineEditSugarAmount widget. The total of the book cost and sugar cost is finally displayed through the labelTotalAmount widget, as shown in the following screenshot:

Using scrollbars and sliders

Scrollbars are useful while looking at large documents or images that cannot appear in a limited visible area. Scrollbars appear horizontally or vertically, indicating your current position in the document or image and the size of the region that is not visible. Using the slider handle provided with these bars, you can access the hidden part of the document or image.

Sliders are a way of selecting an integer value between two values. That is, a slider can represent a minimum and maximum range of values, and the user can select a value within this range by moving the slider handle to the desired location in the slider.

callScrollBar.pyw
0.00MB
demoScrollBar.py
0.00MB
demoScrollBar.ui
0.00MB

 

 

 

Getting ready

Scrollbars are used for viewing documents or images that are larger than the view area. To display horizontal or vertical scrollbars, you use the HorizontalScrollBar and VerticalScrollBar widgets, which are instances of the QScrollBar class. These scrollbars have a slider handle that can be moved to view the area that is not visible. The location of the slider handle indicates the location within the document or image. A scrollbar has the following controls:

  • Slider handle: This control is used to move to any part of the document or image quickly.
  • Scroll arrows: These are the arrows on either side of the scrollbars that are used to view the desired area of the document or image that is not currently visible. On using these scroll arrows, the position of the slider handle moves to show the current location within the document or image.
  • Page control: The page control is the background of the scrollbar over which the slider handle is dragged. When the background is clicked, the slider handle moves towards the click by one page. The amount the slider handle moves can be specified via the pageStep property. The page step is the amount by which a slider moves when the user presses the Page Up and Page Down keys. You can set the amount of the pageStep property by using the setPageStep() method.

The method that is specifically used to set and retrieve values from scrollbars is the value() method, described here.

The value() method fetches the value of the slider handle, that is, its distance value from the start of the scrollbar. You get the minimum value of the scrollbar when the slider handle is at the top edge in a vertical scrollbar or at the left edge in a horizontal scrollbar, and you get the maximum value of the scroll bar when the slider handle is at the bottom edge in a vertical scrollbar or at the right edge in a horizontal scrollbar. You can move the slider handle to its minimum and maximum values via the keyboard too, by pressing the Home and End keys, respectively. Let's take a look at the following methods:

  • setValue(): This method assigns value to the scrollbar and, as per the value assigned, the location of the slider handle is set in the scrollbar
  • minimum(): This method returns the minimum value of the scrollbar
  • maximum(): This method returns the maximum value of the scrollbar
  • setMinimum(): This method assigns the minimum value to the scrollbar
  • setMaximum(): This method assigns the maximum value to the scrollbar
  • setSingleStep(): This method sets the single step value
  • setPageStep(): This method sets the page step value

The signals emitted through the QScrollBar class are shown in the following list:

  • valueChanged(): This signal is emitted when the scrollbar's value is changed, that is, when its slider handle is moved
  • sliderPressed(): This signal is emitted when the user starts to drag the slider handle
  • sliderMoved(): This signal is emitted when the user drags the slider handle
  • sliderReleased(): This signal is emitted when the user releases the slider handle
  • actionTriggered(): This signal is emitted when the scrollbar is changed by user interaction

Sliders are generally used to represent some integer value. Unlike scrollbars, which are mostly used to display large documents or images, the sliders are interactive and an easier way to enter or represent integer values. That is, by moving and positioning its handle along a horizontal or vertical groove, you can make a horizontal or vertical slider to represent some integer value. To display horizontal and vertical sliders, the HorizontalSlider and VerticalSlider widgets are used, which are instances of the QSlider class. Similar to the methods that we saw in scrollbars, the sliders too generate signals such as valueChanged(), sliderPressed(), sliderMoved(), sliderReleased(), and many more on moving the slider handle.

The slider handle in scrollbars and sliders represents a value within the minimum and maximum range. To change the default minimum and maximum values, you can change their values by assigning values to the minimum, maximum, singleStep, and pageStep properties.

Let's create an application consisting of horizontal and vertical scrollbars, as well as horizontal and vertical sliders. The horizontal scrollbar and slider will represent sugar level and blood pressure respectively. That is, on moving the horizontal scroll bar, the sugar level of the patient will be displayed through the Line Edit widget. Similarly, the horizontal slider, when moved, will represent blood pressure and will be displayed through the Line Edit widget.

The vertical scrollbar and slider will represent the heart rate and cholesterol level, respectively. On moving the vertical scrollbar, the heart rate will be displayed via the Line Edit widget and on moving the vertical slider, the cholesterol level will be displayed through the Line Edit widget.

 

 

How to do it...

To understand the working of the horizontal and vertical scrollbars, and the working of the horizontal and vertical sliders, to understand how scrollbars and sliders generate signals when their values are changed, and the how respective slot or method can be associated to them, perform the following steps:

  1. Let's create a new application of the Dialog without Buttons template and drag and drop horizontal and vertical scrollbars and sliders onto the form.
  2. Drop four Label widgets and a Line Edit widget to display the value of the scrollbar and slider handle.
  3. Set the text property of the four Label widgets to Sugar Level, Blood Pressure, Pulse rate, and Cholesterol, respectively.
  4. Set the objectName property of the horizontal scrollbar to horizontalScrollBarSugarLevel, vertical scroll bar to verticalScrollBarPulseRate, horizontal slider to horizontalSliderBloodPressure, and vertical slider to verticalSliderCholestrolLevel.
  5. Set the objectName property of the Line Edit widget to lineEditResult.
  6. Save the application with the name demoSliders.ui.The form will appear as shown in the following screenshot:

The pyuic5 command utility will convert the .ui (XML) file into Python code. The generated Python file, demoScrollBar.py, can be seen in the source code bundle of this book.

  1. Create a Python script file named callScrollBar.pyw that imports the code, demoScrollBar.py, to invoke the user interface design and synchronizes the movement of the scrollbar and slider handles. The script will also display the value of the scrollbar and slider handle with a Label widget. The Python script callScrollBar.pyw will appear, as shown here:

 

How it works...

In this code, you are connecting the valueChanged() signal of each widget with the respective functions so that if the scrollbar or slider handle of the widget is moved, the corresponding function is invoked to perform the desired task. For instance, when the slider handle of the horizontal scrollbar is moved, the scrollhorizontal function is invoked. The scrollhorizontal function displays the value represented by the scrollbar, that is, Sugar Level, through the Label widget. Similarly, when the slider handle of the vertical scrollbar or slider is moved, the scrollvertical function is invoked and the

heart rate, the value of the slider handle of the vertical scrollbar, is displayed through the Label widget, as shown in the following screenshot:

Similarly, when the horizontal and vertical sliders are moved, the blood pressure and cholesterol levels are displayed accordingly, as shown in the following screenshot:

Using List Widget

To display several values in an easier and expandable format, you can use List Widget, which is an instance of the QListWidget class. List Widget displays several items that can not only be viewed, but can be edited and deleted, too. You can add or remove list items one at a time from the List Widget item, or collectively you can set list items by using its internal model.

callListWidget1.pyw
0.00MB
demoListWidget1.py
0.00MB
demoListWidget1.ui
0.00MB

 

 

 

Getting ready

Items in the list are instances of the QListWidgetItem class. The methods provided by QListWidget are shown in the following list:

insertItem(): This method inserts a new item with the supplied text into List Widget at the specified location.

  • insertItems(): This method inserts multiple items from the supplied list, starting at the specified location.
  • count(): This method returns the count of the number of items in the list.
  • takeItem(): This method removes and returns items from the specified row in List Widget.
  • currentItem(): This method returns the current item in the list.
  • setCurrentItem(): This method replaces the current item in the list with the specified item.
  • addItem(): This method appends the item with the specified text at the end of List Widget.
  • addItems(): This method appends items from the supplied list at the end of List Widget.
  • clear(): This method removes all items from List Widget.
  • currentRow(): This method returns the row number of the current selected list item. If no list item is selected, it returns the value -1. setCurrentRow(): This method selects the specified row in List Widget. item(): This method returns the list item at the specified row.

Signals emitted by the QListWidget class are shown in the following list:

  • currentRowChanged(): This signal is emitted when the row of the current list item changes
  • currentTextChanged(): This signal is emitted whenever the text in the current list item is changed
  • currentItemChanged(): This signal is emitted when the focus of the current list item is changed
  • itemClicked()

 

How to do it...

So, let's create an application that displays certain diagnostic tests through List Widget, and that when the user selects any test from List Widget, the selected test is displayed through a Label widget. Here is the step-by-step procedure to create the application:

  1. Create a new application of the Dialog without Buttons template and drag and drop two Label widgets and one List Widget onto the form.
  2. Set the text property of the first Label widget to Choose the Diagnosis Tests.
  3. Set the objectName property of List Widget to listWidgetDiagnosis.
  4. Set the objectName property of the Label widget to labelTest.
  5. Delete the default text property of the labelTest widget as we will display the selected diagnosis test through this widget via code.
  6. To display diagnosis tests through List Widget, right-click on it and from the context menu that opens up, select the Edit Items option.
  7. Add the diagnosis tests one by one, followed by clicking on the + button at the bottom after typing every test, as shown in the following screenshot:
  8. Save the application with the name demoListWidget1.ui. The form will appear as shown in the following screenshot:

The pyuic5 command utility will convert the .ui (XML) file into Python code. The generated Python code, demoListWidget1.py, can be seen in the source code bundle of this book.

  1. Create a Python script file named callListWidget1.pyw that imports the code, demoListWidget1.py, to invoke the user interface design and the code that displays the diagnosis test selected from List Widget. The code in the Python script, callListWidget1.pyw, is as shown here:

How it works...

You can see that the itemClicked event of List Widget is connected to the dispSelectedTest() method. That is, on clicking any of the list items from List Widget, the dispSelectedTest() method is invoked, which uses the currentItem method of List Widget to display the selected item of List Widget through the label called labelTest.

On running the application, you will see List Widget showing a few diagnosis tests; on selecting a test from the List Widget, the test will appear through the Label widget, as shown in the following screenshot:

Selecting multiple list items from one List Widget and displaying them in another

In the preceding application, you were selecting only a single diagnosis test from the List Widget item. What if I want to do multiple selections from the List Widget item? In the case of multiple selections, instead of a Line Edit widget, you need another List Widget to store the selected diagnosis test.

demoListWidget2.ui
0.00MB
demoListWidget3.py
0.00MB

 

 

 

How to do it...

Let's create an application that displays certain diagnosis tests through List Widget and when user selects any test from List Widget, the selected test will be displayed in another List Widget:

  1. So, create a new application of the Dialog without Buttons template and drag and drop two Label widgets and two List Widget onto the form.
  2. Set the text property of the first Label widget as Diagnosis Tests and that of the other to Selected tests are.
  3. Set the objectName property of the first List Widget to listWidgetDiagnosis and of the second List Widget to listWidgetSelectedTests.
  4. To display diagnosis tests through List Widget, right-click on it and from the context menu that opens up, select the Edit Items option.
  5. Add the diagnosis tests one by one followed by clicking on the + button at the bottom after typing every test.
  6. To enable multiple selections from List Widget, select the listWidgetDiagnosis widget and from the Property Editor window, change the selectionMode property from SingleSelection to MultiSelection.
  7. Save the application with the name demoListWidget2.ui. The form will appear as shown in the following screenshot:

By using the pyuic5 utility, the XML file demoListWidget2.ui will be converted into Python code as the demoListWidget2.py file. The generated Python code, from the demoListWidget2.py file, can be seen in the source code bundle of this book.

  1. Create a Python script file named callListWidget2.pyw that imports the code, demoListWidget2.py, to invoke the user interface design and the code that displays the multiple selected diagnosis tests selected from List Widget. The Python script callListWidget2.pyw will appear as shown here:
import sys

from PyQt5.QtWidgets import QDialog, QApplication

from demoListWidget2 import *

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.listWidgetDiagnosis.itemSelectionChanged.connect(self.dispSelectedTest)
        self.show()

    def dispSelectedTest(self):
        self.ui.listWidgetSelectedTests.clear()
        items = self.ui.listWidgetDiagnosis.selectedItems()
        x=[]
        for i in list(items):
            self.ui.listWidgetSelectedTests.addItem(i.text())
            x.append(str(i.text()))

if __name__=="__main__":    
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

 

How it works...

You can see that the itemSelectionChanged event of the first List Widget is connected to the dispSelectedTest() method. That is, on selecting or unselecting any of the list items from the first List Widget item, the dispSelectedTest() method is invoked. The dispSelectedTest() method invokes the selectedItems() method on List Widget to get the list of all the selected items. Thereafter, using the for loop, all the selected items are added to the second List Widget by invoking the addItem() method on it.

On running the application, you will see List Widget showing a few diagnosis tests; on selecting any number of tests from the first List Widget, all the selected tests will appear through the second List Widget item, as shown in the following screenshot:

Adding items into List Widget

Although you can add items to the List Widget item manually through Property Editor, sometimes you need to add items to the List Widget item dynamically through code. Let's create an application that explains the process of adding items to List Widget.

In this application, you will use Label, Line Edit, Push Button, and List Widget. The List Widget item will be empty initially, and the user is asked to enter desired food items into Line Edit and select an Add to List button. The entered food item will then be added to the List Widget item. All subsequent food items will be added below the previous entry.

demoListWidget3.py
0.00MB
demoListWidget3.ui
0.00MB

 

 

 

How to do it...

Perform the following steps to know how items can be added to the List Widget item:

  1. We will begin by creating a new application based on the Dialog without Buttons template and dragging and dropping Label, Line Edit, Push Button, and List Widget onto the form.
  2. Set the text property of the Label and Push Button widgets to Your favourite food item and Add to List, respectively.
  3. Set the objectName property of the Line Edit widget to lineEditFoodItem, that of Push Button to pushButtonAdd, and that of List Widget to listWidgetSelectedItems.
  4. Save the application with the name demoListWidget3.ui. The form will appear as shown in the following screenshot:

On executing the pyuic5 utility, the XML file demoListWidget3.ui will be converted into Python code as demoListWidget3.py. The code of the generated Python file, demoListWidget3.py, can be seen in the source code bundle of this book.

  1. Create a Python script file named callListWidget3.pyw that imports the Python code demoListWidget3.py to invoke the user interface design and adds the food items entered by the user in Line Edit to List Widget. The Python code in the callListWidget3.pyw file will appear as shown here:
import sys

from PyQt5.QtWidgets import QDialog, QApplication

from demoListWidget3 import *

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.pushButtonAdd.clicked.connect(self.addlist)
        self.show()

    def addlist(self):
        self.ui.listWidgetSelectedItems.addItem(self.ui.lineEditFoodItem.text())
        self.ui.lineEditFoodItem.setText('')
        self.ui.lineEditFoodItem.setFocus()

if __name__=="__main__":    
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

 

How it works...

The clicked() event of the Push Button widget is connected to the addlist** function.

Hence, after entering the text to be added to List Widget in the Line Edit widget, when the user selects the Add to List button, the addlist** function is invoked. The addlist** function retrieves the text entered in Line Edit and adds it to List Widget. The text in the Line Edit widget is then removed, and the focus is set on it, enabling the user to enter different text. In the following screenshot, you can see the text entered by the user in the Line Edit widget is added to List Widget when the user selects the Add to List button:

Performing operations in List Widget

In this recipe, you will learn how to perform different operations on list items in List Widget. List Widget is basically used for showing a collection of similar items, enabling the user to choose the desired items. Consequently, you need to add items to List Widget. Also, you might require to edit any item in List Widget. Sometimes, you might require to delete an item from List Widget. One more operation that you might want to perform on List Widget is deleting all items from it, clearing the entire List Widget item. Before learning how to add, edit, and delete items from List Widget, let's understand the concept of a list item.

demoListWidgetOp.py
0.00MB
demoListWidgetOp.ui
0.00MB

 

 

 

Getting ready

List Widget consists of several list items. These list items are instances of the QListWidgetItem class. The list items can be inserted into List Widget using the insertItem() or addItem() methods. List items may be in text or icon form and can be checked or unchecked. Methods provided by QListWidgetItem are given next.

 

Methods provided by the QListWidgetItem class

Let's take a look at the following methods provided by the QListWidgetItem class:

  • setText(): This method assigns the specified text to the list item
  • setIcon(): This method assigns the specified icon to the list item
  • checkState(): This method returns the Boolean value depending on whether the list item is in a checked or unchecked state
  • setHidden(): This method passes the Boolean value true to this method to hide the list item
  • isHidden(): This method returns true if the list item is hidden

We have learned to add items to List Widget. What if you want to edit an existing item in List Widget, or you want to delete an item from List Widget, or you want to delete all the items from List Widget?

Let's learn to perform different operations on List Widget by creating an application. This application will display Line Edit, List Widget, and a couple of Push Button widgets. You can add items to List Widget by entering the text in Line Edit, followed by clicking the Add button. Similarly, you can edit any item from List Widget by clicking an item from List Widget, followed by clicking the Edit button. Not only this, but you can even delete any item from List Widget by clicking the Delete button. If you want to clear the entire List Widget, simply click on the Delete All button.

 

How to do it....

Perform the following steps to understand how different operations can be applied on the List Widget item; how items can be added, edited, and deleted from the List Widget item; and how the entire List Widget item can be cleared:

  1. Open Qt Designer, create a new application based on the Dialog without Buttons template, and drag and drop a Label, Line Edit, four Push Button, and List Widget widgets onto the form.
  2. Set the text property of the Label widget to Enter an item.
  3. Set the text property of the four Push Button widgets to Add, Edit, Delete, and Delete All.
  4. Set the objectName property of the four Push Button widgets to psuhButtonAdd, pushButtonEdit, pushButtonDelete, and pushButtonDeleteAll.
  5. Save the application with the name demoListWidgetOp.ui.

The form will appear as shown in the following screenshot:

The XML file demoListWidgetOp.ui needs to be converted into the Python script by making use of the pyuic5 command utility. The generated Python file demoListWidgetOp.py can be seen in the source code bundle of this book.

  1. Create a Python script file named callListWidgetOp.pyw that imports the Python code, demoListWidgetOp.py, enabling you to invoke the user interface design and add, delete, and edit the list items in List Widget. The code in the Python script callListWidgetOp.pyw is shown here:
import sys

from PyQt5.QtWidgets import QDialog, QApplication, QInputDialog, QListWidgetItem

from demoListWidgetOp import *

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.listWidget.addItem('Ice Cream')
        self.ui.listWidget.addItem('Soda')
        self.ui.listWidget.addItem('Coffee')
        self.ui.listWidget.addItem('Chocolate')
        self.ui.pushButtonAdd.clicked.connect(self.addlist)
        self.ui.pushButtonEdit.clicked.connect(self.editlist)
        self.ui.pushButtonDelete.clicked.connect(self.delitem)
        self.ui.pushButtonDeleteAll.clicked.connect(self.delallitems)
        self.show()

    def addlist(self):
        self.ui.listWidget.addItem(self.ui.lineEdit.text())
        self.ui.lineEdit.setText('')
        self.ui.lineEdit.setFocus()

    def editlist(self):
        row=self.ui.listWidget.currentRow()
        newtext, ok=QInputDialog.getText(self, "Enter new text", "Enter new text")
        if ok and (len(newtext) !=0):
            self.ui.listWidget.takeItem(self.ui.listWidget.currentRow())
            self.ui.listWidget.insertItem(row,QListWidgetItem(newtext))

    def delitem(self):
        self.ui.listWidget.takeItem(self.ui.listWidget.currentRow())

    def delallitems(self):
        self.ui.listWidget.clear()


if __name__=="__main__":    
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

 

How it works...

The clicked() event of pushButtonAdd is connected to the addlist** function. Similarly, the clicked() event of the pushButtonEdit, pushButtonDelete, and pushButtonDeleteAll objects are connected to the editlist, delitem, and delallitems functions, respectively. That is, on clicking any push button, the respective function is invoked. The addlist function calls the addItem function on the List Widget item to add the text entered in the Line Edit widget. The editlist function uses the currentRow method on List Widget to find out the list item to be edited. The getText method of the

QInputDialog class is invoked to prompt the user for the new text or edited text. On clicking the OK button in the dialog, the current list item will be replaced by the text entered in the dialog box. The delitem function invokes the takeItem method on List Widget to delete the current row, that is, the selected list item. The delallitems function invokes the clear method on theList Widget item to clear or delete all the list items from the List Widget item.

On running the application, you will find an empty List Widget, Line Edit, and Add push button below the Line Edit widget. Add any text in the Line Edit widget and click on the Add button to add that item to List Widget. After adding four items to List Widget, it might appear as shown in the following screenshot:

Let's add one more item, Pizza, to List Widget. Type Pizza in the Line Edit widget and click the Add button. The Pizza item will be added to the List Widget item, as shown in the following screenshot:

Assuming we want to edit the Pizza item from List Widget, click the Pizza item in List Widget and click on the Edit button. On clicking the Edit button, you get a dialog box prompting you to enter a new item to replace the Pizza item. Let's enter Cold Drink in the dialog box, followed by clicking the OK button, as shown in the following screenshot:

You can see in the following screenshot that the Pizza item in List Widget is replaced by the text Cold Drink:

In order to delete any item from List Widget, simply click that item from List Widget, followed by clicking the Delete button. Let's click the Coffee item from List Widget and click on the Delete button; the Coffee item will be deleted from List Widget, as shown in the following screenshot:

On clicking the Delete All button, the entire List Widget item will become empty, as shown in the following screenshot:

Using the Combo Box widget

Combo boxes are used for getting input from the user with an applied constraint; that is, the user will be shown certain options in the form of a popup list and he/she can only select from the available choices. A combo box takes less space when compared with List Widget. The QComboBox class is used for displaying combo boxes. Not only can you display text through a combo box, but pixmaps too. Here are the methods provided by the QComboBox class:

Method Usage
setItemText() Sets or changes the text of the item in the combo box.
removeItem() Removes the specific item from the combo box.
clear() Removes all items from the combo box.
currentText() Returns the text of the current item, that is, the item that is currently chosen.
setCurrentIndex() Sets the current index of the combo box, that is, it sets the desired item in the combo box as the currently chosen item.
count() Returns the count of the items in the combo box.
setMaxCount() Sets the maximum number of items that are allowed in the combo box.
setEditable() Make the combo box editable, that is, the user can edit items in the combo box.
addItem() Appends the specified content to the combo box.
addItems() Appends each of the strings supplied in the text to the combo box.
itemText() Returns the text at the specified index location in the combo box.
currentIndex() Returns the index location of the currently chosen item in the combo box. If the combo box is empty or no item is currently chosen in the combo box, the method will return –1 as the index.

 

The following are the signals that are generated by QComboBox:

Signal Description
currentIndexChanged() Emitted when the index of the combo box is changed, that is, the user selects some new item in the combo box.
activated() Emitted when the index is changed by the user.
highlighted() Emitted when the user highlights an item in the combo box.
editTextChanged() Emitted when the text of an editable combo box is changed.

To understand the workings of a combo box practically, let's create a recipe. This recipe will display certain bank account types via a combo box and will prompt the user to choose the type of bank account he/she wants to open. The selected bank account type from the combo box will be displayed on the screen through a Label widget.

 

 

How to do it…

The following are the steps to create an application that makes use of a combo box to show certain options and explains how the selected option from the combo box can be displayed:

  1. Create a new application of the Dialog without Buttons template, drag two Label widgets and a Combo Box widget from the Widget box, and drop them onto the form.
  2. Set the text property of the first Label widget to Select your account type.
  3. Delete the default text property of the second Label widget, as its text will be set through code.
  4. Set the objectName property of the Combo Box widget to comboBoxAccountType.
  5. The second Label widget will be used to display the bank account type that is chosen by the user, so set the objectName property of the second Label widget to labelAccountType.
  6. As we want the Combo Box widget to display certain bank account types, right- click on the Combo Box widget and from the context menu that opens up, select the Edit Items option.
  7. Add some bank account types to the Combo Box widget one by one.
  8. Save the application by name as demoComboBox.ui.
  9. Click the + button displayed at the bottom of the dialog to add a bank account type to the Combo Box widget, as shown in the following screenshot:
  10. After adding the desired bank account types, click on the OK button to exit from the dialog. The form will now appear, as shown in the following screenshot:

The user interface created with Qt Designer is stored in a .ui file, which is an XML file, and needs to be converted to the Python code. The pyuic5 utility can be used for generating Python code from the XML file. The generated file, demoComboBox.py, can be seen in the source code bundle of this book.

  1. Treat the demoComboBox.py file as a header file, and import it to the file from which you will invoke its user interface design that is you will be able to access the combo box.
  2. Create another Python file with the name callComboBox.pyw and import the demoComboBox.py code into it. The code in the Python

How it works...

In the demoComboBox.py file, a class with the name of the top-level object is created with Ui_ prepended. That is, for the top-level object, Dialog, the Ui_Dialog class, is created and stores the interface elements of our widget. That class includes two methods, setupUi and retranslateUi.

The setupUi method creates the widgets that are used in defining the user interface in Qt Designer. Also, the properties of the widgets are set in this method. The setupUi method takes a single argument, which is the top-level widget of the application, an instance of QDialog. The retranslateUi method translates the interface.

In the callComboBox.pyw file, whenever the user selects any item from the combo box, the currentIndexChanged signal will be emitted and the currentIndexChanged signal is connected to the dispAccountType method, so whenever any item is selected from the combo box, the dispAccountType method will be invoked.

In the dispAccountType method, you access the currently selected index number by invoking the currentIndex method of the QComboBox class and passing the fetched index location to the itemText method of the QComboBox class to get the text of the currently selected combo box item. The currently selected combo box item is then displayed through the Label widget.

On running the application, you will find a combo box showing four bank account types: Saving Account, Current Account, Recurring Deposit Account, and Fixed Deposit Account, as shown in the following screenshot:

On selecting a bank account type from the combo box, the chosen bank account type will be displayed through the Label widget, as shown in the following screenshot:

Using the Font Combo Box widget

The Font Combo Box widget, as the name suggests, displays a list of font styles to choose from. The chosen font style can be applied to the desired content if required.

 

Getting ready

To understand the workings of the Font Combo Box widget practically, let's create a recipe. This recipe will display a Font Combo Box widget and a Text Edit widget. The user will be able to type the desired content in the Text Edit widget. After typing the text in the Text Edit widget, when the user selects any font style from the Font Combo Box widget, the selected font will be applied to the content typed into the Text Edit widget.

 

demoFontComboBox.py
0.00MB
demoFontComboBox.ui
0.00MB

 

 

 

How to do it…

Here are the steps to display an active Font Combo Box widget and to apply the selected font to the text written in the Text Edit widget:

  1. Create a new application of the Dialog without Buttons template and drag two Label widgets, a Font Combo Box widget, and a Text Edit widget from the Widget box and drop them onto the form.
  2. Set the text property of the first Label widget to Select desired font and that of the second Label widget to Type some text.
  3. Save the application by name as demoFontComboBox.ui. The form will now appear as shown in the following screenshot:

The user interface created with Qt Designer is stored in a .ui file, which is an XML file, and needs to be converted to the Python code. On converting to Python code, the generated file, demoFontComboBox.py, can be seen in the source code bundle of this book. The preceding code will be used as a header file and is imported into the file in which the GUI is desired, that is, the user interface designed can be accessed in any Python script by simply importing the preceding code.

  1. Create another Python file with the name callFontFontComboBox.pyw and import the demoFontComboBox.py code into it.
import sys

from PyQt5.QtWidgets import QDialog, QApplication

from demoFontComboBox import *

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        myFont=QtGui.QFont(self.ui.fontComboBox.itemText(self.ui.fontComboBox.currentIndex()),15)
        self.ui.textEdit.setFont(myFont)
        self.ui.fontComboBox.currentFontChanged.connect(self.changeFont)
        self.show()

    def changeFont(self):
        myFont=QtGui.QFont(self.ui.fontComboBox.itemText(self.ui.fontComboBox.currentIndex()),15)
        self.ui.textEdit.setFont(myFont)
if __name__=="__main__":    
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

 

How it works...

In the callFontComboBox.pyw file, whenever the user selects any font style from the Font Combo Box widget, the currentFontChanged signal is emitted and this signal is connected to the changeFont method, so whenever any font style is chosen from the Font Combo Box widget, the changeFont() method will be invoked.

In the changeFont() method, you access the selected font style by invoking two methods. The first method invoked is the currentIndex() method of the QFontComboBox class, which fetches the index number of the selected font style. The second method invoked is the itemText() method, and the index location of the currently selected font style is passed to this method to access the chosen font style. The chosen font style is then applied to the content written in the Text Edit widget.

On running the application, you will find a Font Combo Box widget showing available font styles in the system, as shown in the following screenshot:

Type some text in the Text Edit widget and choose the desired font from the font combo box. The chosen font style will be applied to the text written in the Text Edit widget, as shown in the following screenshot:

Using the Progress Bar widget

The Progress Bar widget is very useful in representing the progress of any task. Whether it is downloading a file from a server, virus scanning on a machine, or some other critical task, the Progress Bar widget helps inform the user of the percentage of the task that is done and the percentage that is pending. As the task completes, the Progress Bar widget keeps updating, indicating progress in the task.

demoProgressBar.py
0.00MB
demoProgressBar.ui
0.00MB

 

 

 

Getting ready

To understand how the progress bar is updated to show the progress of any task, let's create a recipe. This recipe will display a Progress Bar widget, indicating the total time required to download a file. When the user clicks the push button to begin downloading the file, the Progress Bar widget will update from 0% to 100% gradually; that is, the progress bar will update as the file is being downloaded. The Progress Bar widget will show 100% when the file is completely downloaded.

How to do it…

Initially, the Progress Bar widget is at 0% and to make it go up, we need to make use of a loop. The loop will increment its value as the task represented by the Progress Bar widget progresses towards completion. Every increment in the loop value will add to some progress in the Progress Bar widget. Here is the step-by-step procedure to show how a progress bar can be updated:

  1. Create a new application from the Dialog without Buttons template, and drag a Label widget, a Progress Bar widget, and a Push Button widget from the Widget box and drop them onto the form.
  2. Set the text property of the Label widget to Downloading the file and that of the Push Button widget to Start Downloading.
  3. Set the objectName property of the Push Button widget to pushButtonStart.
  4. Save the application by name as demoProgressBar.ui. The form will now appear, as shown in the following screenshot:

The user interface created with Qt Designer is stored in a .ui file, which is an XML file and needs to be converted into Python code. The generated Python code, demoProgressBar.py, can be seen in the source code bundle of this

book. The preceding code will be used as a header file and is imported into the file in which the GUI is desired; that is, the user interface designed in the code can be accessed in any Python script by simply importing the preceding code.

  1. Create another Python file with the name callProgressBar.pyw and import the demoProgressBar.py code into it. The code in the Python

 

import sys

from PyQt5.QtWidgets import QDialog, QApplication

from demoProgressBar import *

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.pushButtonStart.clicked.connect(self.updateBar)
        self.show()

    def updateBar(self):
        x = 0
        while x < 100:
            x += 0.0001
            self.ui.progressBar.setValue(x)

if __name__=="__main__":    
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

 

How it works...

In the callProgressBar.pyw file, because we want the progress bar to show its progress when the push button is pressed, the clicked() event of the progress bar is connected to the updateBar() method, so when the push button is clicked, the updateBar() method will be invoked. In the updateBar() method, a while loop is used that loops from 0 to 100. A variable, x, is initialized to the value 0. With every iteration of the while loop, the value of x is incremented by 0.0001. The value in the x variable is applied to the progress bar when updating it. That is, with every iteration of the while loop, the value of x is incremented and the value of x is used in updating the progress bar. Hence, the progress bar will begin its progress at 0% and continue until it reaches 100%.

On running the application, initially, you will find the Progress Bar widget at 0% along with the push button at the bottom with the caption Start Downloading (see the following screenshot). Click the Start Downloading push button and you will see that the progress bar begins showing progress gradually. The progress bar keeps going up until it reaches 100% to indicate that the file is completely downloaded:

'Qt5 Python GUI Programming Cookbook' 카테고리의 다른 글

Understanding Dialogs  (0) 2023.02.28
Understanding OOP Concepts  (0) 2023.02.28
Working with Date and Time  (0) 2023.02.28
Creating a User Interface with Qt Components  (0) 2023.02.27
index  (0) 2023.02.27

댓글