Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Qt5 Python GUI Programming Cookbook
Qt5 Python GUI Programming Cookbook

Qt5 Python GUI Programming Cookbook: Building responsive and powerful cross-platform applications with PyQt

eBook
₹799.99 ₹3276.99
Paperback
₹4096.99
Subscription
Free Trial
Renews at ₹800p/m
:

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Qt5 Python GUI Programming Cookbook

Creating a User Interface with Qt Components

In this chapter, we will learn to use the following widgets:

  • Displaying a welcome message
  • Using the Radio Button widget
  • Grouping radio buttons
  • Displaying options in the form of checkboxes
  • Displaying two groups of checkboxes

Introduction

We will be learning to create GUI applications using the Qt toolkit. The Qt toolkit, known simply as Qt, is a cross-platform application and UI framework developed by Trolltech, which is used for developing GUI applications. It runs on several platforms, including Windows, macOS X, Linux, and other UNIX platforms. It is also referred to as a widget toolkit because it provides widgets such as buttons, labels, textboxes, push buttons, and list boxes, which are required for designing a GUI. It includes a cross-platform collection of classes, integrated development tools, and a cross-platform IDE. To create real-time applications, we will be making use of Python bindings for the Qt toolkit called, PyQt5.

PyQt

PyQt is a set of Python bindings for the cross-platform application framework that combines all the advantages of Qt and Python. With PyQt, you can include Qt libraries in Python code, enabling you to write GUI applications in Python. In other words, PyQt allows you to access all the facilities provided by Qt through Python code. Since PyQt depends on the Qt libraries to run, when you install PyQt, the required version of Qt is also installed automatically on your machine.

A GUI application may consist of a main window with several dialogs or just a single dialog. A small GUI application usually consists of at least one dialog. A dialog application contains buttons. It doesn't contain a menu bar, toolbar, status bar, or central widget, whereas a main window application normally has all of those.

Dialogs are of the following two types:

  • Modal: This dialog is one that blocks the user from interacting with other parts of the application. The dialog is the only part of the application that the user can interact with. Until the dialog is closed, no other part of the application can be accessed.
  • Modeless: This dialog is the opposite of a modal dialog. When a modeless dialog is active, the user is free to interact with the dialog and with the rest of the application.

Ways of creating GUI applications

There are the following two ways to write a GUI application:

  • From scratch, using a simple text editor
  • With Qt Designer, a visual design tool with which you can create a user interface quickly using drag and drop

You will be using Qt Designer to develop GUI applications in PyQt, as it is a quick and easy way to design user interfaces without writing a single line of code. So, launch Qt Designer by double-clicking on its icon on desktop.

On opening, Qt Designer asks you to select a template for your new application, as shown in the following screenshot:

Qt Designer provides a number of templates that are suitable for different kinds of applications. You can choose any of these templates and then click the Create button.

Qt Designer provides the following predefined templates for a new application:

  • Dialog with Buttons Bottom: This template creates a form with the OK and Cancel buttons in the bottom-right corner.
  • Dialog with Buttons Right: This template creates a form with the OK and Cancel buttons in the top-right corner.
  • Dialog without Buttons: This template creates an empty form on which you can place widgets. The superclass for dialogs is QDialog.
  • Main Window: This template provides a main application window with a menu bar and a toolbar that can be removed if not required.
  • Widget: This template creates a form whose superclass is QWidget rather than QDialog.

Every GUI application has a top-level widget and the rest of the widgets are called its children. The top-level widget can be QDialog, QWidget, or QMainWindow, depending on the template you require. If you want to create an application based on the dialog template, then the top-level widget or the first class that you inherit will be QDialog. Similarly, to create an application based on the Main Window template, the top-level widget will be QMainWindow, and to create the application based on the Widget template, you need to inherit the QWidget class. As mentioned previously, the rest of the widgets that are used for the user interface are called child widgets of the classes.

Qt Designer displays a menu bar and toolbar at the top. It shows a Widget box on the left that contains a variety of widgets used to develop applications, grouped in sections. All you have to do is drag and drop the widgets you want from the form. You can arrange widgets in layouts, set their appearance, provide initial attributes, and connect their signals to slots.

Displaying a welcome message

In this recipe, the user will be prompted to enter his/her name followed by clicking a push button. On clicking the button, a welcome message will appear, "Hello," followed by the name entered by the user. For this recipe, we need to make use of three widgets, Label, Line Edit, and Push Button. Let's understand these widgets one by one.

Understanding the Label widget

The Label widget is an instance of the QLabel class and is used for displaying messages and images. Because the Label widgets simply display results of computations and don't take any input, they are simply used for supplying information on the screen. 

Methods

The following are the methods provided by the QLabel class:

  • setText(): This method assigns text to the Label widget
  • setPixmap(): This method assigns pixmap, an instance of the QPixmap class, to the Label widget
  • setNum(): This method assigns an integer or double value to the Label widget
  • clear(): This method clears text from the Label widget

The default text of QLabel is TextLabel. That is, when you add a QLabel class to a form by dragging a Label widget and dropping it on the form, it will display TextLabel. Besides using setText(), you can also assign text to a selected QLabel object by setting its text property in the Property Editor window.

Understanding the Line Edit widget

The Line Edit widget is that is popularly used for entering single-line data. The Line Edit widget is an instance of the QLineEdit class, and you can not only enter, but also edit the data too. Besides entering data, you can undo, redo, cut, and paste data in the Line Edit widget. 

Methods

The following are the methods provided by the QLineEdit class:

  • setEchoMode(): It sets the echo mode of the Line Edit widget. That is, it determines how the contents of the Line Edit widget are to be displayed. The available options are as follows:
  • Normal: This is the default mode and it displays characters the way they are entered
  • NoEcho: It switches off the Line Edit echo, that is, it doesn't display anything
  • Password: This option is used for password fields, no text will be displayed; instead, asterisks appear for the text entered by the user
  • PasswordEchoOnEdit: It displays the actual text while editing the password fields, otherwise it will display the asterisks for the text
  • maxLength(): This method is used to specify the maximum length of text that can be entered in the Line Edit widget. 
  • setText(): This method is used for assigning text to the Line Edit widget.
  • text(): This method accesses the text entered in the Line Edit widget.
  • clear(): This method clears or deletes the complete content of the Line Edit widget.
  • setReadOnly(): When the Boolean value true is passed to this method, it will make the Line Edit widget read-only, that is, non-editable. The user cannot make any changes to the contents displayed through the Line Edit widget, but can only copy. 
  • isReadOnly(): This method returns the Boolean value true if the Line Edit widget is in read-only mode, otherwise it returns false.
  • setEnabled(): By default, the Line Edit widget is enabled, that is, the user can make changes to it. But if the Boolean value false is passed to this method, it will disable the Line Edit widget so the user cannot edit its content, but can only assign text via the setText() method.
  • setFocus(): This method positions the cursor on the specified Line Edit widget.

Understanding the Push Button widget

To display a push button in an application, you need to create an instance of the QPushButton class. When assigning text to buttons, you can create shortcut keys by preceding any character in the text with an ampersand. For example, if the text assigned to a push button is Click Me, the character C will be underlined to indicate that it is a shortcut key, and the user can select the button by pressing Alt + C. The button emits the clicked() signal if it is activated. Besides text, an icon can also be displayed in the push button. The methods for displaying text and an icon in a push button are as follows:

  • setText(): This method is used to assign text to the push button
  • setIcon(): This method is used to assign an icon to the push button

How to do it...

Let's create a new application based on the Dialog without Buttons template. As said earlier, this application will prompt the user to enter a name and, on clicking the push button after entering a name, the application with display a hello message along with the entered name. Here are the steps to create this application:

  1. Drag a Label widget from the Display Widgets category and drop it on the form. Set its text property to Enter your name. Set the objectName property of the Label widget to labelResponse.
  2. Drag one more Label widget from the Display Widgets category and drop it on the form. Do not change the text property of this Label widget and leave its text property to its default value, TextLabel. This is because the text property of this Label widget will be set through code, that is, it will be used to display the hello message to the user.
  3. Drag one Line Edit from the Input Widgets category and drop it on the form. Set its objectName property to lineEditName.
  4. Drag one Push Button widget from the Buttons category and drop it onto the form. Set its text property to Click. You can change the text property of the Push Button widget through any of three ways: by double-clicking the Push Button widget and overwriting the default text, by right-clicking the Push Button widget and selecting the Change text... option from the context menu that pops up, or by selecting the text property from the Property Editor window and overwriting the default text.
  5. Set the objectName property of the Push Button widget to ButtonClickMe.
  1. Save the application with the name demoLineEdit.ui. Now the form will appear, as shown in the following screenshot:

The user interface that you create with Qt Designer is stored in a .ui file that includes all the form's information: its widgets, layout, and so on. The .ui file is an XML file, and you need to convert it to Python code. That way, you can maintain a clear separation between the visual interface and the behavior implemented in code.

  1. To use the .ui file, you first need to convert it into a Python script. The command utility that you will use for converting a .ui file into a Python script is pyuic5. In Windows, the pyuic5 utility is bundled with PyQt. To do the conversion, you need to open a Command Prompt window and navigate to the folder where the file is saved and issue the following command:
C:\Pythonbook\PyQt5>pyuic5 demoLineEdit.ui -o demoLineEdit.py

Let's assume that we saved the form at this location: C:\Pythonbook\PyQt5>. The preceding command shows the conversion of the demoLineEdit.ui file into a Python script, demoLineEdit.py.

The Python code generated by this method should not be modified manually, as any changes will be overwritten the next time you run the pyuic5 command.

The code of the generated Python script file, demoLineEdit.py, can be seen in the source code bundle of this book.

  1. Treat the code in the demoLineEdit.py file as a header file, and import it to the file from which you will invoke its user interface design.
The header file is a term referred to those files which are imported into the current file. The command to import such files is usually written at the top in the script, hence named as header files. 
  1. Let's create another Python file with the name callLineEdit.py and import the demoLineEdit.py code into it as follows:
import sys
from PyQt5.QtWidgets import QDialog, QApplication
from demoLineEdit import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.ButtonClickMe.clicked.connect(self.dispmessage)
self.show()
def dispmessage(self):
self.ui.labelResponse.setText("Hello "
+self.ui.lineEditName.text())
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyForm()
w.show()
sys.exit(app.exec_())

How it works...

The demoLineEdit.py file is very easy to understand. A class with the name of the top-level object is created, with Ui_ prepended. Since the top-level object used in our application is Dialog, the Ui_Dialog class is created and stores the interface elements of our widget. That class has two methods, setupUi() and retranslateUi(). The setupUi() method sets up the widgets; it creates the widgets that you use while defining the user interface in Qt Designer. The method creates the widgets one by one and also sets their properties. The setupUi() method takes a single argument, which is the top-level widget in which the user interface (child widgets) is created. In our application, it is an instance of QDialog. The retranslateUi() method translates the interface.

Let's understand what callLineEdit.py does statement-wise:

  1. It imports the necessary modules. QWidget is the base class of all user interface objects in PyQt5.
  2. It creates a new MyForm class that inherits from the base class, QDialog.
  3. It provides the default constructor for QDialog. The default constructor has no parent, and a widget with no parent is known as a window.
  4. Event handling in PyQt5 uses signals and slots. A signal is an event, and a slot is a method that is executed on the occurrence of a signal. For example, when you click a push button, a clicked() event, also known as a signal, occurs. The connect() method connects signals with slots. In this case, the slot is a method: dispmessage(). That is, when the user clicks the push button, the dispmessage() method will be invoked. clicked() is an event here and an event handling loop waits for an event to occur and then dispatches it to perform some task. The event handling loop continues to work until either the exit() method is called or the main widget is destroyed.
  5. It creates an application object with the name app through the QApplication() method. Every PyQt5 application must create sys.argv application object which contains a list of arguments from the command line, and it is passed to the method while creating the application object. The sys.argv parameter helps in passing and controlling the startup attributes of a script.
  1. An instance of the MyForm class is created with the name w.
  2. The show() method will display the widget on the screen.
  3. The dispmessage() method performs event handling for the push button. It displays the Hello text, along with the name entered in the Line Edit widget.
  4. The sys.exit() method ensures a clean exit, releasing memory resources.
The exec_() method has an underscore because exec is a Python keyword.

On executing the preceding program, you get a window with the Line Edit and Push Button widgets, as shown in the following screenshot. When the push button is selected, the displmessage() method will be executed, displaying the Hello message along with the user's name that is entered in the Line Edit widget:

Using the Radio Button widget

This recipe displays certain flight types via Radio Button and when the user selects the radio button, the price associated with that flight will be displayed. We need to first understand the workings of Radio Button

Understanding Radio Button

The Radio Button widgets are very popular when you want the user to select only one option out of the available options. Such options are known as mutually exclusive options. When the user selects an option, the previously selected option is automatically deselected. The Radio Button widgets are instances of the QRadioButton class. Every radio button has an associated text label. The radio button can be either in selected (checked) or unselected (unchecked) states. If you want two or more sets of radio buttons, where each set allows the exclusive selection of a radio button, put them into different button groups (instances of QButtonGroup). The methods provided by QRadioButton are shown next.

Methods 

The QRadioButton class provides the following methods:

  • isChecked(): This method returns the Boolean value true if the button is in the selected state.
  • setIcon(): This method displays an icon with the radio button.
  • setText(): This method assigns the text to the radio button. If you want to specify a shortcut key for the radio button, precede the preferred character in the text with an ampersand (&). The shortcut character will be underlined.
  • setChecked(): To make any radio button appear selected by default, pass the Boolean value true to this method.

Signal description

Signals emitted by QRadioButton are as follows:

  • toggled(): This signal is emitted whenever the button changes its state from checked to unchecked or vice versa
  • clicked(): This signal is emitted when a button is activated (that is, pressed and released) or when its shortcut key is pressed
  • stateChanged(): This signal is emitted when a radio button changes its state from checked to unchecked or vice versa

To understand the concept of radio buttons, let's create an application that asks the user to select the flight type and displays three options, First Class, Business Class, and Economy Class, in the form of radio buttons. On selecting an option through the radio button, the price for that flight will be displayed.

How to do it...

Let's create a new application based on the Dialog without Buttons template. This application will display different flight types along with their respective prices. When a user selects a flight type, its price will be displayed on the screen:

  1. Drag and drop two Label widgets and three Radio Button widgets onto the form.
  2. Set the text property of the first Label widget to Choose the flight type and delete the text property of the second Label widget. The text property of the second Label widget will be set through code; it will be used to display the price of the selected flight type.
  3. Set the text property of the three Radio Button widgets to First Class $150, Business Class $125, and Economy Class $100.
  4. Set the objectName property of the second Label widget to labelFare. The default object names of the three radio buttons are radioButton, radioButton_2, and radioButton_3. Change the objectName property of these three radio buttons to radioButtonFirstClass, radioButtonBusinessClass, and radioButtonEconomyClass.
  5. Save the application with name demoRadioButton1.ui.

Take a look at the following screenshot: 

The demoRadioButton1.ui application is an XML file and needs to be converted into Python code through the pyuic5 command utility. The generated Python code, demoRadioButton1.py, can be seen in the source code bundle of this book.

  1. Import the demoRadioButton1.py file as a header file in the Python script that you are going to create next to invoke the user interface design.
  2. In the Python script, write the code to display the flight type on the basis of the radio button selected by the user. Name the source file callRadioButton1.py; its code is shown here:
import sys
from PyQt5.QtWidgets import QDialog, QApplication
from demoRadioButton1 import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.radioButtonFirstClass.toggled.connect(self.
dispFare)
self.ui.radioButtonBusinessClass.toggled.connect(self.
dispFare)
self.ui.radioButtonEconomyClass.toggled.connect(self.
dispFare)
self.show()
def dispFare(self):
fare=0
if self.ui.radioButtonFirstClass.isChecked()==True:
fare=150
if self.ui.radioButtonBusinessClass.isChecked()==True:
fare=125
if self.ui.radioButtonEconomyClass.isChecked()==True:
fare=100
self.ui.labelFare.setText("Air Fare is "+str(fare))
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyForm()
w.show()
sys.exit(app.exec_())

How it works...

The toggled() event of Radio Button is connected to the dispFare() function, which will display the price of the selected flight type. In the dispFare() function, you check the state of the radio buttons. Hence, if radioButtonFirstClass is selected, the value 50 is assigned to the fare variable. Similarly, if radioButtonBusinessClass is selected, the value 125 is assigned to the fare variable. Similarly, the value 100 is assigned to the fare variable when radioButtonEconomyClass is selected. Finally, the value in the fare variable is displayed via labelFare.

On executing the previous program, you get a dialog that displays three flight types and prompts the user to select the one that he/she wants to use for travel. On selecting a flight type, the price of the selected flight type is displayed, as shown in the following screenshot:

Grouping radio buttons

In this application, we will learn to create two groups of radio buttons. The user can select radio buttons from either group and accordingly the result or text will appear on the screen.

Getting ready

We will display a dialog that displays shirts of different sizes and different payment methods. On selecting a shirt size and a payment method, the selected shirt size and payment method will be displayed on the screen. We will create two groups of radio buttons, one of the shirt sizes and other payment methods. The shirt size group displays four radio buttons showing four different types of the size such as M, L, XL, and XXL, where M stands for medium size, L stands for large size, and so on. The payment method group displays three radio buttons, Debit/Credit Card, NetBanking, and Cash On Delivery. The user can select any radio button from either of the groups. When the user selects any of the shirt sizes or payment methods, the selected shirt size and payment method will be displayed.

How to do it...

Let's recreate the preceding application step by step:

  1. Create a new application based on the Dialog without Buttons template.
  2. Drag and drop three Label widgets and seven Radio Button widgets. Out of these seven radio buttons, we will arrange four radio buttons in one vertical layout and the other three radio buttons in the second vertical layout. The two layouts will help in grouping these radio buttons. Radio buttons being mutually exclusive will allow only one radio button to be selected from a layout or group.
  3. Set the text property of the first two Label widgets to Choose your Shirt Size and Choose your payment method respectively.
  4. Delete the text property of the third Label widget because we will display the selected shirt size and payment method through the code.
  5. In the Property Editor window, increase the font size of all the widgets to increase their visibility in the application.
  6. Set the text property of the first four radio buttons to MLXL, and XXL. Arrange these four radio buttons into one vertical layout.
  7. Set the text property of the next three radio buttons to Debit/Credit Card, NetBanking, and Cash On Delivery. Arrange these three radio buttons into a second vertical layout. Remember, these vertical layouts help by grouping these radio buttons.
  8. Change the object names of the first four radio buttons to radioButtonMedium, radioButtonLarge, radioButtonXL, and radioButtonXXL.
  1. Set the objectName property of the first VBoxLayout layout to verticalLayout. The VBoxLayout layout will be used for aligning radio buttons vertically.
  2. Change the object names of next three radio buttons to radioButtonDebitCard, radioButtonNetBanking, and radioButtonCashOnDelivery.
  3. Set the objectName property of the second QVBoxLayout object to verticalLayout_2.
  4. Set the objectName property of the third Label widget to labelSelected. It is through this Label widget that the selected shirt size and payment method will be displayed.
  5. Save the application with the name demoRadioButton2.ui.
  6. Now, the form will appear, as shown in the following screenshot:

The .ui (XML) file is then converted into Python code through the pyuic5 command utility. You can find the Python code, demoRadioButton2.py, in the source code bundle for this book.

  1. Import the demoRadioButton2.py file, as a header file in our program to invoke the user interface design and to write code to display the selected shirt size and payment method through a Label widget when the user selects or unselects any of the radio buttons.
  1. Let's name the program callRadioButton2.pyw; its code is shown here:
import sys
from PyQt5.QtWidgets import QDialog, QApplication
from demoRadioButton2 import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.radioButtonMedium.toggled.connect(self.
dispSelected)
self.ui.radioButtonLarge.toggled.connect(self.
dispSelected)
self.ui.radioButtonXL.toggled.connect(self.dispSelected)
self.ui.radioButtonXXL.toggled.connect(self.
dispSelected)
self.ui.radioButtonDebitCard.toggled.connect(self.
dispSelected)
self.ui.radioButtonNetBanking.toggled.connect(self.
dispSelected)
self.ui.radioButtonCashOnDelivery.toggled.connect(self.
dispSelected)
self.show()
def dispSelected(self):
selected1="";
selected2=""
if self.ui.radioButtonMedium.isChecked()==True:
selected1="Medium"
if self.ui.radioButtonLarge.isChecked()==True:
selected1="Large"
if self.ui.radioButtonXL.isChecked()==True:
selected1="Extra Large"
if self.ui.radioButtonXXL.isChecked()==True:
selected1="Extra Extra Large"
if self.ui.radioButtonDebitCard.isChecked()==True:
selected2="Debit/Credit Card"
if self.ui.radioButtonNetBanking.isChecked()==True:
selected2="NetBanking"
if self.ui.radioButtonCashOnDelivery.isChecked()==True:
selected2="Cash On Delivery"
self.ui.labelSelected.setText("Chosen shirt size is
"+selected1+" and payment method as " + selected2)
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyForm()
w.show()
sys.exit(app.exec_())

How it works...

The toggled() event of all the radio buttons is connected to the dispSelected() function, which will display the selected shirt size and payment method. In the dispSelected() function, you check the status of the radio buttons to find out whether they are checked or unchecked. On the basis of the selected radio button in the first vertical layout, the value of the selected1 variable will be set to Medium, Large, Extra Large, or Extra Extra Large. Similarly, from the second vertical layout, depending on the radio button selected, the value of the selected2 variable will be initialized to Debit/Credit Card, NetBanking, or Cash On Delivery. Finally, the shirt size and payment method assigned to the selected1 variable and selected variables will be displayed via the labelSelected widget. On running the application, you get a dialog prompting you to select the shirt size and payment method. On selecting a shirt size and payment method, the selected shirt size and payment method are displayed via the Label widget, as shown in the following screenshot:

Displaying options in the form of checkboxes

While creating applications, you may come across a situation where you need to provide several options for the user to select from. That is, you want the user to select one or more than one option from a set of options. In such situations, you need to make use of checkboxes. Let's find out more about checkboxes.

Getting ready

Whereas radio buttons allow only one option to be selected in a group, checkboxes allow you to select more than one option. That is, selecting a checkbox will not affect other checkboxes in the application. Checkboxes are displayed with a text label as an instance of the QCheckBox class. A checkbox can be in any of three states: selected (checked), unselected (unchecked), or tristate (unchanged). Tristate is a no change state; the user has neither checked nor unchecked the checkbox. 

Method application

The following are the methods provided by the QCheckBox class:

  • isChecked(): This method returns the Boolean value true if the checkbox is checked, and otherwise returns false.
  • setTristate(): If you don't want the user to change the state of the checkbox, you pass the Boolean value true to this method. The user will not be able to check or uncheck the checkbox.
  • setIcon(): This method is used to display an icon with the checkbox.
  • setText(): This method assigns text to the checkbox. To specify a shortcut key for the checkbox, precede the preferred character in the text with an ampersand. The shortcut character will appear as underlined.
  • setChecked(): In order to make a checkbox appear as checked by default, pass the Boolean value true to this method.

Signal description

The signals emitted by QCheckBox are as follows:

  • clicked(): This signal is emitted when a checkbox is activated (that is, pressed and released) or when its shortcut key is pressed
  • stateChanged(): This signal is emitted whenever a checkbox changes its state from checked to unchecked or vice versa

To understand the Check Box widget, let's assume that you run a restaurant where several food items, such as pizzas, are sold. The pizza is sold along with different toppings, such as extra cheese, extra olives, and so on, and the price of each topping is also mentioned with it. The user can select a regular pizza with one or more toppings. What you want is that when a topping is selected, the total price of the pizza, including the selected topping, is displayed.

How to do it...

The focus of this recipe is to understand how an action is initiated when the state of a checkbox changes from checked to unchecked or vice versa. Following is the step-by-step procedure to create such an application:

  1. Begin by creating a new application based on the Dialog without Buttons template.
  2. Drag and drop three Label widgets and three Check Box widgets onto the form.
  3. Set the text property of the first two Label widgets to Regular Pizza $10 and Select your extra toppings.
  4. In the Property Editor window, increase the font size of all three labels and checkboxes to increase their visibility in the application.
  5. Set the text property of the three checkboxes to Extra Cheese $1, Extra Olives $1, and Extra Sausages $2. The default object names of the three checkboxes are checkBox, checkBox_2, and checkBox_3.
  6. Change these to checkBoxCheese, checkBoxOlives, and checkBoxSausages, respectively.
  7. Set the objectName property of the Label widget to labelAmount.
  1. Save the application with the name demoCheckBox1.ui. Now, the form will appear as shown in the following screenshot:

The .ui (XML) file is then converted into Python code through the pyuic5 command utility. The Python code generated in the demoCheckBox1.py file can be seen in the source code bundle of this book.

  1. Import the demoCheckBox1.py file, as a header file in our program to invoke the user interface design and to write code to calculate the total cost of regular pizza, along with the selected toppings, through a Label widget when the user selects or unselects any of the checkboxes.
  2. Let's name the program callCheckBox1.pyw; its code is shown here:
import sys
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from demoCheckBox1 import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.checkBoxCheese.stateChanged.connect(self.
dispAmount)
self.ui.checkBoxOlives.stateChanged.connect(self.
dispAmount)
self.ui.checkBoxSausages.stateChanged.connect(self.
dispAmount)
self.show()
def dispAmount(self):
amount=10
if self.ui.checkBoxCheese.isChecked()==True:
amount=amount+1
if self.ui.checkBoxOlives.isChecked()==True:
amount=amount+1
if self.ui.checkBoxSausages.isChecked()==True:
amount=amount+2
self.ui.labelAmount.setText("Total amount for pizza is
"+str(amount))
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyForm()
w.show()
sys.exit(app.exec_())

How it works...

The stateChanged() event of checkboxes is connected to the dispAmount function, which will calculate the cost of the pizza along with the toppings selected. In the dispAmount function, you check the status of the checkboxes to find out whether they are checked or unchecked. The cost of the toppings whose checkboxes are checked is added and stored in the amount variable. Finally, the addition of the amount stored in the amount variable is displayed via labelAmount. On running the application, you get a dialog prompting you to select the toppings that you want to add to your regular pizza. On selecting any toppings, the amount of the regular pizza along with the selected toppings will be displayed on the screen, as shown in the following screenshot:

The dispAmount function will be invoked every time the status of any checkbox changes. As a result, the total amount will be displayed via the Label widget, as soon as any checkbox is checked or unchecked.

Displaying two groups of checkboxes

In this application, we will learn to make two groups of checkboxes. The user can select any number of checkboxes from either group and, accordingly, the result will appear.

Getting ready

We will try displaying a menu of a restaurant where different types of ice creams and drinks are served. We will create two groups of checkboxes, one of ice creams and the other of drinks. The ice cream group displays four checkboxes showing four different types of ice cream, mint chocolate chip, cookie dough, and so on, along with their prices. The drinks group displays three checkboxes, coffee, soda, and so on, along with their prices. The user can select any number of checkboxes from either of the groups. When the user selects any of the ice creams or drinks, the total price of the selected ice creams and drinks will be displayed.

How to do it...

Here are the steps to create an application, which explain how checkboxes can be arranged into different groups and how to take respective action when the state of any checkbox from any group changes:

  1. Create a new application based on the Dialog without Buttons template.
  2. Drag and drop four Label widgets, seven Check Box widgets, and two Group Box widgets onto the form.
  3. Set the text property of the first three Label widgets to Menu, Select your IceCream, and Select your drink respectively.
  4. Delete the text property of the fourth Label widget because we will display the total amount of the selected ice creams and drinks through the code.
  5. Through Property Editor, increase the font size of the all the widgets to increase their visibility in the application.
  6. Set the text property of the first four checkboxes to Mint Choclate Chips $4, Cookie Dough $2, Choclate Almond $3, and Rocky Road $5. Put these four checkboxes into the first group box.
  7. Set the text property of the next three checkboxes to Coffee $2, Soda $3, and Tea $1 respectively. Put these three checkboxes into the second group box.
  1. Change the object names of the first four checkboxes to checkBoxChoclateChips, checkBoxCookieDough, checkBoxChoclateAlmond, and checkBoxRockyRoad.
  2. Set the objectName property of the first group box to groupBoxIceCreams.
  3. Change the objectName property of the next three checkboxes to checkBoxCoffee, checkBoxSoda, and checkBoxTea.
  4. Set the objectName property of the second group box to groupBoxDrinks.
  5. Set the objectName property of the fourth Label widget to labelAmount.
  6. Save the application with the name demoCheckBox2.ui. It is through this Label widget that the total amount of the selected ice creams and drinks will be displayed, as shown in the following screenshot:

The .ui (XML) file is then converted into Python code through the pyuic5 command utility. You can find the generated Python code, the demoCheckbox2.py file, in the source code bundle of this book.

  1. Import the demoCheckBox2.py file as a header file in our program to invoke the user interface design, and to write code to calculate the total cost of ice creams and drinks through a Label widget when the user selects or unselects any of the checkboxes.
  2. Let's name the program callCheckBox2.pyw; its code is shown here:
import sys
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from demoCheckBox2 import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.checkBoxChoclateAlmond.stateChanged.connect
(self.dispAmount)
self.ui.checkBoxChoclateChips.stateChanged.connect(self.
dispAmount)
self.ui.checkBoxCookieDough.stateChanged.connect(self.
dispAmount)
self.ui.checkBoxRockyRoad.stateChanged.connect(self.
dispAmount)
self.ui.checkBoxCoffee.stateChanged.connect(self.
dispAmount)
self.ui.checkBoxSoda.stateChanged.connect(self.
dispAmount)
self.ui.checkBoxTea.stateChanged.connect(self.
dispAmount)
self.show()
def dispAmount(self):
amount=0
if self.ui.checkBoxChoclateAlmond.isChecked()==True:
amount=amount+3
if self.ui.checkBoxChoclateChips.isChecked()==True:
amount=amount+4
if self.ui.checkBoxCookieDough.isChecked()==True:
amount=amount+2
if self.ui.checkBoxRockyRoad.isChecked()==True:
amount=amount+5
if self.ui.checkBoxCoffee.isChecked()==True:
amount=amount+2
if self.ui.checkBoxSoda.isChecked()==True:
amount=amount+3
if self.ui.checkBoxTea.isChecked()==True:
amount=amount+1
self.ui.labelAmount.setText("Total amount is
$"+str(amount))
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyForm()
w.show()
sys.exit(app.exec_())

How it works...

The stateChanged() event of all the checkboxes is connected to the dispAmount function, which will calculate the cost of the selected ice creams and drinks. In the dispAmount function, you check the status of the checkboxes to find out whether they are checked or unchecked. The cost of the ice creams and drinks whose checkboxes are checked is added and stored in the amount variable. Finally, the addition of the amount stored in the amount variable is displayed via the labelAmount widget. On running the application, you get a dialog prompting you to select the ice creams or drinks that you want to order. On selecting the ice creams or drinks, the total amount of the chosen items will be displayed, as shown in the following screenshot:

  

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Get succinct QT solutions to pressing GUI programming problems in Python
  • Learn how to effectively implement reactive programming
  • Build customized applications that are robust and reliable

Description

PyQt is one of the best cross-platform interface toolkits currently available; it's stable, mature, and completely native. If you want control over all aspects of UI elements, PyQt is what you need. This book will guide you through every concept necessary to create fully functional GUI applications using PyQt, with only a few lines of code. As you expand your GUI using more widgets, you will cover networks, databases, and graphical libraries that greatly enhance its functionality. Next, the book guides you in using Qt Designer to design user interfaces and implementing and testing dialogs, events, the clipboard, and drag and drop functionality to customize your GUI. You will learn a variety of topics, such as look and feel customization, GUI animation, graphics rendering, implementing Google Maps, and more. Lastly, the book takes you through how Qt5 can help you to create cross-platform apps that are compatible with Android and iOS. You will be able to develop functional and appealing software using PyQt through interesting and fun recipes that will expand your knowledge of GUIs

Who is this book for?

If you’re an intermediate Python programmer wishing to enhance your coding skills by writing powerful GUIs in Python using PyQT, this is the book for you.

What you will learn

  • Use basic Qt components, such as a radio button, combo box, and sliders
  • Use QSpinBox and sliders to handle different signals generated on mouse clicks
  • Work with different Qt layouts to meet user interface requirements
  • Create custom widgets and set up customizations in your GUI
  • Perform asynchronous I/O operations and thread handling in the Python GUI
  • Employ network concepts, internet browsing, and Google Maps in UI
  • Use graphics rendering and implement animation in your GUI
  • Make your GUI application compatible with Android and iOS devices

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 30, 2018
Length: 462 pages
Edition : 1st
Language : English
ISBN-13 : 9781788831000
Vendor :
Qt
Category :
Languages :
Tools :
:

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 30, 2018
Length: 462 pages
Edition : 1st
Language : English
ISBN-13 : 9781788831000
Vendor :
Qt
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 11,396.97
Python GUI Programming with Tkinter
₹3649.99
Qt5 Python GUI Programming Cookbook
₹4096.99
Hands-On GUI Programming with C++ and Qt5
₹3649.99
Total 11,396.97 Stars icon
Banner background image

Table of Contents

14 Chapters
Creating a User Interface with Qt Components Chevron down icon Chevron up icon
Event Handling - Signals and Slots Chevron down icon Chevron up icon
Working with Date and Time Chevron down icon Chevron up icon
Understanding OOP Concepts Chevron down icon Chevron up icon
Understanding Dialogs Chevron down icon Chevron up icon
Understanding Layouts Chevron down icon Chevron up icon
Networking and Managing Large Documents Chevron down icon Chevron up icon
Doing Asynchronous Programming in Python Chevron down icon Chevron up icon
Database Handling Chevron down icon Chevron up icon
Using Graphics Chevron down icon Chevron up icon
Implementing Animation Chevron down icon Chevron up icon
Using Google Maps Chevron down icon Chevron up icon
Running Python Scripts on Android and iOS Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.4
(9 Ratings)
5 star 11.1%
4 star 0%
3 star 22.2%
2 star 55.6%
1 star 11.1%
Filter icon Filter
Top Reviews

Filter reviews by




Caroline Rose Sep 21, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I agree with the intro to this book that says Harwani can explain "even the most complicated topics in a straightforward and easily understandable fashion.” His organization and presentation reflect his experience teaching actual live students the topics he writes about. Each task section starts out with minimal introductory info, followed by clear, succinct, amply illustrated steps to take (“How to do it”), and only then does it give more details (“How it works”), which you can read to the extent that you want to or need to. I’m not a Python programmer and so have not gone through this particular book thoroughly, but I’ve used parts of other books by this author and found them to be excellent. What I mainly am is an experienced, very fussy technical writer and editor, and I don’t heap praise on authors lightly; in this case, I think it’s well deserved. You can’t go wrong with a book by B.M. Harwani.
Amazon Verified review Amazon
TORDJMAN Jan 03, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Good for base programming
Amazon Verified review Amazon
snigg Mar 13, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Its a cookbook. So there is almost zero technical background and sometimes one is asking whether the author really does know the things behind. Technical people who want to learn should find something else. This book is for the ones that want to do and do not ask how it works and why.For me as a none native english reader (obviously) the stereotypical figures of speech start to annoy me after a while. I wish that book publisher would invest more in correction and keep a cleaner english language.
Amazon Verified review Amazon
schloss5020 Aug 25, 2021
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Unter ein Kochbuch stelle ich mir etwas anderes vor
Amazon Verified review Amazon
Quel Geek Jun 30, 2019
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
If you've read no similar book then by all means consider this one. As I write, this book is the just latest of its sort. It probably fills a place in its publisher's catalogue. It is not a bad book but there were already others just as good. It covers no new ground and you won't be building "powerful" applications just because you read it. That book is yet to be written.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.