46,44 €
Over 60 recipes to help you design interactive, smart, and cross-platform GUI applications
Key Features
Book 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
What you will learn
Who this book is 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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 444
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Richa TripathiAcquisition Editor: Alok Dhuri Content Development Editor: Zeeyan PinheiroTechnical Editor: Vibhuti GawdeCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Rekha NairGraphics: Jason MonteiroProduction Coordinator: Nilesh Mohite
First published: July 2018
Production reference: 1270718
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-100-0
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
B.M. Harwani is the founder and owner of Microchip Computer Education (MCE), based in Ajmer, India. He graduated with a BE in computer engineering from the University of Pune and also has a C level (masters diploma in computer technology) from DOEACC, Government of India. Having been involved in the teaching field for over 20 years, he has developed the art of explaining even the most complicated topics in a straightforward and easily understandable fashion. He is also a renowned speaker and the author of several books. To learn more, visit his blog, a site that helps programmers.
Marcus Ottosson is a company director, software developer, and artist with a decade of experience in the film and visual effects industry. He has built countless user interfaces and tools with Python and Qt for projects such as Marvel’s Doctor Strange and Alfonso Cuaron’s Gravity. He has written several Python frameworks for use in the creation of film and games, such as Pyblish and Avalon, along with PyQt, a compatibility wrapper around all the available bindings of Qt for Python.
Sivan Grünberg has close to 20 years of multidisciplinary IT expertise and a razor-sharp eye for quality. A long-time open source devotee, his contributions can be found, literally, all over open source. He has been utilizing the Python ecosystem for R&D endeavors ever since it was pitched to him by The SABDFL and Ubuntu. Alongside Shir, a product, content, and operations expert, he runs Vitakka.co, providing infrastructure consulting and coding solutions in all-things digital.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Qt5 Python GUI Programming Cookbook
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Get in touch
Reviews
Creating a User Interface with Qt Components
Introduction
PyQt
Ways of creating GUI applications
Displaying a welcome message
Understanding the Label widget
Methods
Understanding the Line Edit widget
Methods
Understanding the Push Button widget
How to do it...
How it works...
Using the Radio Button widget
Understanding Radio Button
Methods 
Signal description
How to do it...
How it works...
Grouping radio buttons
Getting ready
How to do it...
How it works...
Displaying options in the form of checkboxes
Getting ready
Method application
Signal description
How to do it...
How it works...
Displaying two groups of checkboxes
Getting ready
How to do it...
How it works...
Event Handling - Signals and Slots
Introduction
Using Signal/Slot Editor
How to do it...
Copying and pasting text from one Line Edit widget to another
Getting ready
How to do it...
How it works...
Converting data types and making a small calculator
How to do it...
How it works...
Using the Spin Box widget
Getting ready
How to do it...
How it works...
Using scrollbars and sliders
Getting ready
How to do it...
How it works...
Using List Widget
Getting ready
How to do it...
How it works...
Selecting multiple list items from one List Widget and displaying them in another
How to do it...
How it works...
Adding items into List Widget
How to do it...
How it works...
Performing operations in List Widget
Getting ready
Methods provided by the QListWidgetItem class
How to do it....
How it works...
Using the Combo Box widget
How to do it…
How it works...
Using the Font Combo Box widget
Getting ready
How to do it…
How it works...
Using the Progress Bar widget
Getting ready
How to do it…
How it works...
Working with Date and Time
Displaying LCD digits
Using Timers
Using the QTime class
Displaying system clock time in LCD-like digits
How to do it...
How it works...
Displaying the date selected by the user from Calendar Widget
Getting ready
Displaying a calendar
Using the QDate class
Using the Date Edit widget
How to do it...
How it works...
Creating a hotel reservation form 
Getting ready
How to do it...
How it works...
Displaying tabular data using Table Widget
Getting ready
Table Widget
The QTableWidgetItem class
How to do it...
How it works...
Understanding OOP Concepts
Object-oriented programming
Creating a class
Using the built-in class attributes
Accessing class variables in instance methods
Instances
Using classes in GUI
How to do it...
How it works...
Making the application more elaborate
Inheritance
Types of inheritance
Using single inheritance
Getting ready
How to do it...
How it works...
Using multilevel inheritance
Getting ready
How to do it...
How it works...
Using multiple inheritance
Getting ready
How to do it...
How it works...
Understanding Dialogs
Introduction
The input dialog box
Using the input dialog 
How to do it...
How it works...
Using the color dialog
How to do it...
How it works...
Using the font dialog
How to do it...
How it works...
Using the file dialog
Getting ready
How to do it...
How it works...
Understanding Layouts
Understanding layouts
Spacers
Using Horizontal Layout
How to do it...
How it works...
Using Vertical Layout
How to do it...
How it works...
Using Grid Layout
How to do it...
How it works...
Using Form Layout
Getting ready
How to do it...
How it works...
Networking and Managing Large Documents
Introduction
Creating a small browser
How to do it...
How it works...
Creating a server-side application
How to do it...
How it works...
Establishing client-server communication
How to do it...
How it works...
Creating a dockable and floatable sign-in form
Getting ready
How to do it...
How it works...
Multiple Document Interface 
Getting ready
How to do it...
How it works...
Displaying information in sections using Tab Widget
How to do it...
How it works...
Creating a custom menu bar
How to do it…
How it works...
Doing Asynchronous Programming in Python
Introduction
Multithreading
Asynchronous programming
Updating progress bar using thread
How to do it...
How it works...
Updating two progress bars using two threads
How to do it...
How it works...
Updating progress bars using threads bound with a locking mechanism
How to do it...
How it works...
Updating progress bars simultaneously using asynchronous operations
How to do it...
How it works...
Managing resources using context manager
Context manager
How to do it…
How it works...
Database Handling
Introduction
Creating the cursor object
Creating a database
How to do it…
How it works…
Creating a database table
How to do it…
How it works…
Inserting rows in the specified database table
How to do it…
How it works…
Displaying rows in the specified database table
How to do it…
How it works…
Navigating through the rows of the specified database table
How to do it…
How it works…
Searching a database table for specific information
How to do it…
How it works…
Creating a signin form – applying an authentication procedure
How to do it…
How it works…
Updating a database table – changing a user's password 
How to do it…
How it works…
Deleting a row from a database table
How to do it…
How it works…
Using Graphics
Introduction
Displaying mouse coordinates
How to do it...
How it works...
Displaying coordinates where the mouse button is clicked and released
How to do it...
How it works...
Displaying a point where the mouse button is clicked
How to do it...
How it works...
Drawing a line between two mouse clicks
How to do it...
How it works...
Drawing lines of different types
How to do it...
How it works...
Drawing a circle of a desired size
How to do it...
How it works...
Drawing a rectangle between two mouse clicks
How to do it...
How it works...
Drawing text in a desired font and size
How to do it...
How it works...
Creating a toolbar that shows different graphics tools
How to do it…
How it works...
Plotting a line using Matplotlib
Getting ready
How to do it...
How it works...
Plotting a bar using Matplotlib
Getting ready
How to do it...
How it works...
Implementing Animation
Introduction
Implementing animation
Displaying a 2D graphical image
How to do it...
How it works...
Making a ball move down on the click of a button
How to do it...
How it works...
Making a bouncing ball
How to do it...
How it works...
Making a ball animate as per the specified curve
How to do it...
How it works...
Using Google Maps
Introduction
Finding out details of a location or a landmark
How to do it…
How it works…
Getting complete information from latitude and longitude values
How to do it…
How it works…
Finding out the distance between two locations
How to do it…
How it works…
Displaying location on Google Maps 
How to do it…
How it works…
Running Python Scripts on Android and iOS
Introduction
Copying scripts from PC to Android devices
How to do it
Prompting for a username and displaying a welcome message
How to do it...
How it works...
Understanding different buttons in a dialog box
How to do it...
How it works...
Performing single selection from a list
How to do it...
How it works...
Performing multiple selections from a list
How to do it...
How it works...
Displaying a Date Picker dialog
How to do it...
How it works...
Capturing images using a camera
How to do it...
How it works...
Making an Android device speak a text input
How to do it...
How it works...
Creating a cross-platform Python script using Kivy
Getting started
How to do it...
Packaging a Python Script into the Android APK using Buildozer
Getting ready
How to do it...
How it works
Packaging Python script for iOS
How to do it...
How it works...
Other Books You May Enjoy
Leave a review - let other readers know what you think
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 you need 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. The book shows you how to use QT Designer to design user interfaces and implement and test 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 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.
This book is meant for intermediate to advanced programmers and developers who have some preliminary knowledge of Python programming. This book can be of great use for trainers, teachers, and software developers who wish to build a fully-featured GUI-based application in Python.
Chapter 1, Creating a User Interface with Qt Components, teaches readers to use certain basic widgets of Qt Designer and how to display a welcome message along with the username. You will also be learning how to choose one out of several options using radio buttons and choose more than one out of several options by making use of checkboxes.
Chapter 2, Event Handling – Signals and Slots, covers how to execute specific tasks on the occurrence of certain events on any widget, how to copy and paste text from one Line Edit widget to another, convert data types and make a small calculator, and use spin boxes, scrollbars, and sliders. You will also learn to perform multiple tasks using the List Widget.
Chapter 3, Working with Date and Time, focuses on learning how to display the system clock time using an LCD, show the date selected by the user from Calendar Widget, create a hotel reservation form, and display tabular data using Table widget.
Chapter 4, Understanding OOP Concepts, discusses object-oriented programming concepts such as how to use classes, single inheritance, multilevel inheritance in GUI applications, and multiple inheritance.
Chapter 5, Understanding Dialogs, explores the use of certain dialogs, where each dialog is meant for fetching a different kind of information. You will also learn to take input from the user using input dialog.
Chapter 6, Understanding Layouts, explains how to arrange widgets horizontally, vertically, and in different layouts by making use of Horizontal Layout, Vertical Layout, Grid Layout, and arranging widgets in two column layout using Form Layout.
Chapter 7, Networking and Managing Large Documents, demonstrates how to make a small browser, establish a connection between client and server, create a dockable and floatable sign in form, and manage more than one document using MDI. Also, you will be learn how to display information in sections using the Tab widget. You will learn how to create a custom menu bar that invokes different graphics tools when a specific menu item is chosen.
Chapter 8, Doing Asynchronous Programming in Python, looks at the concept of asynchronous operations using threads. To see the impact of asynchronous operations on GUIs, you will be making use of a progress bar, that is, the progress bars will be updated through threads asynchronously.
Chapter 9, Database Handling, outlines how to manage a SQLite database to keep information for future use. Using the knowledge gained, you will learn to make a signin form that checks whether a user's email address and password are correct or not.
Chapter 10, Using Graphics, explains how to display certain graphics in the application. You will also learn how to create a toolbar of your own that contains certain tools that can be used to draw different graphics.
Chapter 11, Implementing Animation, features how to display a 2D graphical image, make a ball move down on the click of a button, make a bouncing ball, and make a ball animate as per the specified curve.
Chapter 12, Using Google Maps, showcases how to use the Google API to display location and other information. You will learn to derive the distance between two locations and display location on Google Maps on the basis of longitude and latitude values that are entered.
Chapter 13, Running Python Scripts on Android and iOS devices, takes you through how to use QPython to run Python scripts on Android devices. You will learn how to package Kivy Python scripts on Android and iOS devices. You will be making several applications for mobile devices, such as prompting for the user’s name and displaying a welcome message, understanding different buttons in a Dialog box, performing single and multiple selections from a list, selecting date using a Date Picker dialog, capturing images using a camera, making Android devices speak text, creating cross-platform Python scripts using Kivy, packaging Python scripts into the Android APK using Buildozer, and packaging Python scripts for iOS.
You need to have some preliminary knowledge of Python programming. You need to install Python and PyQt5. The steps to install Python and PyQt are explained in the Appendix. To run Python script on Android devices, you need to install QPython on your Android device. To package Python scripts into Android’s APK using the Kivy library, you need to install Kivy, a Virtual Box, and Buildozer packager. Similarly, to run Python scripts on iOS devices, you need a macOS machine and some library tools, including Cython. The steps to install these software are explained in Chapter 13, Running Python Scripts on Android and iOS.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Qt5-Python-GUI-Programming-Cookbook. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/Qt5PythonGUIProgrammingCookbook_ColorImages.pdf.
In this book, you will find several headings that appear frequently (Getting ready,How to do it..., How it works..., There's more..., and Seealso).
To give clear instructions on how to complete a recipe, use these sections as follows:
This section tells you what to expect in the recipe and describes how to set up any software or anypreliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you moreknowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
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
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 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.
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.
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.
The Label widget is an instance of theQLabelclass 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.
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 a
ssigns an integer or double value to the
Label
widget
clear()
:
This method c
lears 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.
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.
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.
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
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:
It imports the necessary modules.
QWidget
is the base class of all user interface objects in PyQt5.
It creates a new
MyForm
class that inherits from the base class,
QDialog
.
It provides the default constructor for
QDialog
. The default constructor has no parent, and a widget with no parent is known as a window.
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.
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.
An instance of the
MyForm
class is created with the name
w
.
The
show()
method will display the widget on the screen.
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.
The
sys.exit()
method ensures a clean exit, releasing memory resources.
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:
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.
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.
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.
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.
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:
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.
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.
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
