Python GUI with PyQt: Learn to build modern and stunning GUIs in Python with PyQt5 and Qt Designer (English Edition)
()
About this ebook
The book starts with the basics of GUI programming, such as creating windows, using layout managers, and managing signals and events. It then covers more advanced topics, such as creating dialog and message boxes, using container, input, item views, and display widgets. Then it teaches you to connect signals to slots, the cornerstone of event-driven programming, and discover how to utilize Qt Designer, a visual GUI design tool, to streamline the development process. As you progress, delve into the realm of containers, learning to organize and manage widgets with finesse. Explore the vast array of input widgets, enabling users to seamlessly provide data. You finally conclude your journey by mastering the art of display widgets, empowering you to present information with clarity and elegance. The book is also highly interactive, with practical examples and exercises at the end of each chapter. These help you solidify your understanding of the concepts and gain practical experience in PyQt5 GUI programming.
Overall, this is an excellent book for anyone who wants to learn how to create GUI applications in Python using PyQt5 and Qt Designer.
Read more from Saurabh Chandrakar
Building Modern GUIs with tkinter and Python: Building user-friendly GUI applications with ease (English Edition) Rating: 0 out of 5 stars0 ratingsPython for Everyone: Learn and polish your coding skills in Python (English Edition) Rating: 0 out of 5 stars0 ratingsProgramming Techniques using Python: Have Fun and Play with Basic and Advanced Core Python Rating: 0 out of 5 stars0 ratings
Related to Python GUI with PyQt
Related ebooks
Data Structure in Python: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsMastering PyCharm Rating: 5 out of 5 stars5/5PySide GUI Application Development - Second Edition Rating: 0 out of 5 stars0 ratingsKivy Blueprints Rating: 0 out of 5 stars0 ratingsNew Learning of Python by Practical Innovation and Technology Rating: 0 out of 5 stars0 ratingsKivy – Interactive Applications and Games in Python - Second Edition Rating: 0 out of 5 stars0 ratingsInteractive Applications Using Matplotlib Rating: 0 out of 5 stars0 ratingsUltimate Neural Network Programming with Python Rating: 0 out of 5 stars0 ratingsPython Unlocked Rating: 0 out of 5 stars0 ratingsNumPy Recipes Rating: 0 out of 5 stars0 ratingsExploring the Python Library Ecosystem: A Comprehensive Guide Rating: 0 out of 5 stars0 ratingsFoundations of Data Intensive Applications: Large Scale Data Analytics under the Hood Rating: 0 out of 5 stars0 ratingsChemical Engineering: Advancing Sustainable Solutions Through Innovative Processes and Systems Rating: 0 out of 5 stars0 ratingsScientific Computing with Scala Rating: 0 out of 5 stars0 ratingsPython Unleashed: Mastering the Art of Efficient Coding Rating: 0 out of 5 stars0 ratingsLearning PyTorch 2.0, Second Edition: Utilize PyTorch 2.3 and CUDA 12 to experiment neural networks and deep learning models Rating: 0 out of 5 stars0 ratingsDynamic Programming in Java: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsMastering CUDA Python Programming Rating: 0 out of 5 stars0 ratingsLearning jqPlot Rating: 0 out of 5 stars0 ratingsMastering Python Advanced Concepts and Practical Applications Rating: 0 out of 5 stars0 ratingsNumPy Essentials Rating: 0 out of 5 stars0 ratingsMastering Time Series Analysis and Forecasting with Python Rating: 0 out of 5 stars0 ratingsApplied Deep Learning: Design and implement your own Neural Networks to solve real-world problems (English Edition) Rating: 0 out of 5 stars0 ratingsIntroduction to TinyML Rating: 5 out of 5 stars5/5Neo4j High Performance Rating: 0 out of 5 stars0 ratingsLearning Apache Mahout Classification Rating: 0 out of 5 stars0 ratingsWeb App Testing Using Knockout.JS Rating: 0 out of 5 stars0 ratings
Programming For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsLearn SQL in 24 Hours Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsLearn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5PYTHON PROGRAMMING Rating: 4 out of 5 stars4/5iPhone For Dummies Rating: 0 out of 5 stars0 ratingsAutomate the Boring Stuff with Python, 2nd Edition: Practical Programming for Total Beginners Rating: 4 out of 5 stars4/5HTML, CSS, and JavaScript Mobile Development For Dummies Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5
Reviews for Python GUI with PyQt
0 ratings0 reviews
Book preview
Python GUI with PyQt - Saurabh Chandrakar
C
HAPTER
1
Introduction to PyQt5 and Qt Designer Tool
Introduction
In our previously launched book Building Modern GUIs with tkinter and Python, we learned how to create GUI forms using the Tk interface library. Now, we will be looking at another approach to create the same GUI forms using one of the most popular cross-platform libraries, known as PyQt5 library, which was developed by Riverbank Computing. A robust and cross-platform graphical toolkit called Qt has a Python binding called PyQt5. Python is a well-known and simple-to-learn programming language, and with PyQt5 developers, we can simply construct GUI applications using Python. With PyQt5, a visual layout tool called Qt Designer is included. Without having to write any code explicitly, it enables developers to construct GUI layouts quickly and easily by dragging and dropping widgets onto a canvas. Additionally, Qt Designer offers a selection of editable widgets that may be used to design distinctive user interfaces with eye-catching visuals.
Structure
In this chapter, we will discuss the following topics:
Comparison of PyQt5 with tkinter library
PyQt5 framework installation
First GUI form creation using PyQt5 without using class
GUI form creation using PyQt5 by using class
Installation of Qt Designer tool with pre-defined templates
Components of Qt Designer
User Credential App Demo
Objectives
By the end of this chapter, the reader will be able to compare the powerful and cross-platform toolkit graphical PyQt5, with the tkinter library. We shall see how to install the PyQt5 framework installation, along with the creation of a basic GUI form using PyQt5, first without, and then using the class. Moreover, we will be looking into the components inside Qt Designer along with different pre-defined templates. Finally, we will be creating a user credential app, initially focusing on the view in Qt Designer (.ui file which is a XML file), then converting it into a Python code (.py) using pyuic5 command, and finally creating a new Python file, which will be importing the Python code for user interface design and adding some useful logic to create a basic login application for the user.
Comparison of PyQt5 with tkinter library
There are numerous Qt classes in a set of Python modules, which are compatible with many operating systems such as iOS, Windows, Linux, Unix, Android, and so on, which is a part of the top-level Python package, that is, PyQt5 library. Qt5 in PyQt5 stands for Qt version 5. This library provides us the advantage of Python binding with the Qt C++ toolkit. An important point to note is that under the GNU General Public License (GNU GPL or GPL) v3 license, the PyQt5 license is being released. One may wonder that if we have already learned about tkinter, then why we should learn about PyQt5 as well? To better understand this, let us check the advantages of PyQt5 over other library packages such as tkinter:
Flexibility in coding: In order to establish simple communication between objects, there is a concept of signals and slots, which gives us flexibility for GUI programming using PyQt5, when dealing with events.
More than GUI toolkit: Using PyQt5, we can build entire applications using its graphics, printer support, networking, database access, and so on. It is like an application framework.
Numerous UI components: PyQt5 offers numerous widgets such as QLabel, QButton, QCombobox, and so on, such that each widget has some basic image well suited in all the platforms. Numerous advanced widgets are also available on the topic in this library.
Numerous study resources: If there is no documentation, then you might wonder what the point of learning is. PyQt5 comes with a rich array of documentation since it is one of the most commonly used Python packages for GUI creation.
Easy to understand: We can easily use previous knowledge of either Python, Qt or C++, thus making PyQt5 easy to understand.
Preferred choice of GUI developers: Due to simplicity and ease of use, many GUI developers opt for functionalities that come with PyQt5 to develop their own applications.
GUI widget appearance: The appearance of PyQt5 is nice and pleasing to the eyes.
Now, we may wonder which library to choose to create GUI forms using PyQt5 or tkinter. This generally depends on user application and the willingness to learn and explore. Table 1.1 further shows the differences between the libraries:
Table 1.1: Differences between libraries PyQt5 and tkinter
You can decide which library to choose to create GUI forms, depending on your application. We will later discuss how to create a UI form using Qt Designer in detail, as well as the widgets associated with it and the Python code with logic written by importing the auto-code generated by creating the UI form in detail.
PyQt5 framework installation
The Python version we will be using for discussing PyQt5 will be 3.7.3. (You can try working with new version as on today, that is, 3.11.5 dated Aug 24, 2023) From the location where we have installed our Python, first type the command python --version to check the version installed and then type the following command to install pyqt5:
pip install pyqt5
Refer to Figure 1.1:
Figure 1.1: PyQt5 installation
Once installed, we can verify the installation of PyQt5 under Python site-packages folder, as shown in Figure 1.2:
Figure 1.2: PyQt5 folder
We can check some of the modules present in PyQt5. If we do not get any error, then we can again cross verify that PyQt5 is successfully installed, as shown in Figure 1.3:
Figure 1.3: PyQt5 package verification
First GUI form creation using PyQt5 without using class
Now, we shall see a basic UI form creation using PyQt5 without using class. This is quite important. As you might have realized, most of the UI forms which we will be creating will be using the concept of class and object. It is highly recommended that you go through the concept of class before moving further in this chapter. It is well explained in our previous books, Programming Techniques using Python and Python for Everyone. Here, we will only focus on our basic UI form creation. So, without any further delay, let us start. Refer to the following code which can be checked in some IEDs like VSCode, Spyder, Anaconda and so on:
import sys # L1
from PyQt5.QtWidgets import QWidget, QApplication # L2
myapp = QApplication(sys.argv) # L3
mywindow = QWidget() # L4
mywindow.show() # L5
sys.exit(myapp.exec_()) # L6
Output:
The output can be seen in the following Figure 1.4:
Figure 1.4: Output of Chap1_Example1.py
You will be surprised that by writing few lines of code, we can create our GUI form, and that too, as fully functional. Now let us see the explanation of this code, line by line.
In L1, we are first importing the sys module for accessing the command line arguments.
In L2, we are importing from class, which creates desktop style UIs of PyQt5 package, that is, Qt Widgets. QWidget is used for creating an empty GUI and QApplication is nothing but an application handler. We can see that from the above statement, we are importing the modules for creating the GUI form.
In L3, we are creating an instance, that is, object of QApplication class using the variable name myapp and passing command-line parameters list sys.argv to the application. When we are sure that we will be passing command line parameters to control Qt form through shell launching or during the course of interface automating, we can pass this as an argument to QApplication class, or else we can pass as an empty list as:
myapp = QApplication([])
In L4, we are creating an object of QWidget class using the variable name mywindow. This QWidget class is the parent class of all the User Interface objects in Qt. The top-level window is created by not passing any parameter to the QWidget class.
In L5, in order to make the widgets visible after creating the object of QWidget class, we must call show() method with the object. Now, you may wonder what will happen if we do not call this show method. Since after running the application, there is no way to close or quit it, show() will be called to simply display widgets.
In L6, for implementing parallel execution, PyQt5 uses an event-loop mechanism as it is largely written in C++, So, to start up the event-loop mechanism, we are calling myapp.exec_() method, which will be held by the application object. Some will even think that at some places, we have seen myapp.exec. This exec was a reserved word in Python 2. So, to avoid the naming conflict with this reserved word, we are using exec_() in PyQt5. Therefore, when there will be a requirement by the user to close the GUI, this myapp.exec_() will allow the control to pass over to Qt to terminate the application. Just try using Ctrl + C to terminate the application as done in our Python programs. You will find out that the application will not be terminated. Now, if we want our code to return gracefully and not to raise SystemExit exception, this event loop mechanism functionality is to be wrapped in a function and should return from the place where we intend to use sys.exit. Therefore, any exceptions that may be thrown or might occur, must exit cleanly using the following statement:
sys.exit(myapp.exec_())
You will be wondering that in the above code, many classes start with a capital letter Q so that it can be distinguished from other namespaces.
We can resize the window, drag it around to any conformable place, maximize it or close it. Just make sure that do not use the following, as it is best to avoid wild imports:
fromPyQt5.Qtwidgets import *
One important point to observe is that the GUI form comes up with the default title Python and with default size.
Now, let us put some of our own title text in Python GUI form:
import sys
from PyQt5.QtWidgets import QWidget, QApplication
myapp = QApplication(sys.argv)
mywindow = QWidget()
mywindow.setWindowTitle('Basic GUI Form') # BG1
mywindow.show()
sys.exit(myapp.exec_())
Output:
The output can be seen in the following Figure 1.5:
Figure 1.5: Output of Chap1_Example2.py
In BG1, we are calling setWindowTitle() method from QWidget object and passing parameter as Basic GUI Form. Therefore, we can see that our GUI form has a title that we wanted to display at the top-left. The rest of the code is the same as previous program.
Now, we can also specify the size of our GUI form, that is, by specifying width and height by calling the resize method as shown:
import sys
from PyQt5.QtWidgets import QWidget, QApplication
myapp = QApplication(sys.argv)
mywindow = QWidget()
mywindow.setWindowTitle('Basic GUI Form')
mywindow.resize(400,350) # RS1
mywindow.show()
sys.exit(myapp.exec_())
Output:
The output can be seen in the following Figure 1.6:
Figure 1.6: Output of Chap1_Example3.py
In RS1, we are calling the resize() method using the QWidget object and passing parameters as 400 and 300. So, here we are setting width as 400 and height as 300, which sets our GUI form.
Therefore, we have learned the basic structure of creating a GUI form using PyQt5 without the usage of class.
Now, we will learn the similar examples , with usage of classes and objects concept.
GUI form creation using PyQt5 by using class
It is very important that you understand the concept of objects and classes. Before we proceed further, one program can be written in n number of ways. The best approach is to program systematically, in a structured way with as few lines as possible. Let us learn the same examples by creating class approach:
import sys # CL1
from PyQt5.QtWidgets import QWidget, QApplication # CL2
class GUIWindow(QWidget):
def __init__(self):
super(GUIWindow, self).__init__() # CL6
self.initializationUI() # CL7
def initializationUI(self):
self.show() # CL8
if __name__ == '__main__':
myapp = QApplication(sys.argv) # CL3
mywindow = GUIWindow() #CL4
sys.exit(myapp.exec_()) # CL5
Output:
The output can be seen in the following Figure 1.7:
Figure 1.7: Output of Chap1_Example4.py
Explanation of CL1, CL2, CL3 and CL5 is similar to that of L1, L2, L3 and L6 of code Chap1_Example1.py
In CL4, we are creating an object of user-defined class GUIWindow class. We can see that GUIWindow class is being derived from the parent class QWidget, from which spaces and windows are inherited either directly or indirectly. Moreover, all UI objects will be derived from this QWidget class.
In CL6, we are calling the __init__ method of our parent class QWidget. In other words, we can say that the default constructor of QWidget class is created.
In CL7, we have created the initializationUI method in our GUIWindow class.
In CL8, inside the initializationUI method, we are calling the show method on our GUI Window object for displaying:
import sys # CL1
from PyQt5.QtWidgets import QWidget, QApplication # CL2
class GUIWindow(QWidget):
def __init__(self):
super(GUIWindow, self).__init__() # CL6
self.initializationUI() # CL7
def initializationUI(self):
self.setWindowTitle(Basic GUI Form
) #CL9
self.show() # CL8
if __name__ == '__main__':
myapp = QApplication(sys.argv) # CL3
mywindow = GUIWindow() #CL4
sys.exit(myapp.exec_()) # CL5
Output:
The output can be seen in the following Figure 1.8:
Figure 1.8: Output of Chap1_Example5.py
In the above code, everything is similar to that of code Chap1_Example4.py except that in CL9, we are calling setWindowTitle() method on our GUI Window object and passing the parameter as Basic GUI Form. This will set the title to the text at the top-left side of the GUI form, as shown:
import sys # CL1
from PyQt5.QtWidgets import QWidget, QApplication # CL2
class GUIWindow(QWidget):
def __init__(self):
super(GUIWindow, self).__init__() # CL6
self.initializationUI() # CL7
def initializationUI(self):
self.setGeometry(300,300,400,300) # CL10
self.setWindowTitle(Basic GUI Form
) # CL9
self.show() # CL8
if __name__ == '__main__':
myapp = QApplication(sys.argv) # CL3
mywindow = GUIWindow() #CL4
sys.exit(myapp.exec_()) # CL5
Output:
The output can be seen in the following Figure 1.9:
Figure 1.9: Output of Chap1_Example6.py
In the above code, everything is similar to that of code Chap1_Example5.py except that in CL10, we are trying to define the geometry of PyQt5 GUI form by setting the four arguments :
self.setGeometry(300,300,400,300) (# self.setGeometry(x-axis, y-axis, width, height))
The first argument is X-coordinate, which is set as 300.
The second argument is Y-coordinate, which is set as 300.
The third argument is window width, which is set as 400.
The fourth argument is window height, which is set as 300.
So, we can see that with the help of the usage of classes as well, we can create a GUI form, set the title, define the geometry, and neatly exit the form.
Now, we have written some lines of code to get our desired result. What if we can just create our own GUI form by using some user interface design tool. We are lucky that we can create the same GUI forms that we have seen till now using interface tools such as Qt Designer. Now, we will learn all the GUI forms using Qt Designer tool from here.
Qt Designer is one of the handiest tools for designing your imagination into a working product by building GUI forms with existing Qt Widgets. In this book, we will cover the creation and usage of Qt Designer widgets and its interfaces to create newly designed UI forms. We will study about the concept of signals and slots, drag and drop interfaces, customization of signals, dialogs, windows, and so on. For more documentation on Qt Designer and some other insights, you may visit the official website through the link: https://doc.qt.io/qt-6/qt-intro.html
Installation of Qt Designer with pre-defined templates
Till now, we have seen that for any package we want to install, we will be using the pip command. But Qt Designer cannot be installed in your system using pip command like this pip install pyQt Designer. So, you can either download it from sourceforge or install it using pip install pyqt5-tools.
After this, run the designer from the following path:
C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python37\Lib\site-packages\pyqt5-tools\designer\designer.exe.
Launch the Qt Designer application, and on executing, the following GUI window, as shown in Figure 1.10, will be displayed to the user. Here, we can create our own GUI forms as per our need:
Figure 1.10: Qt Designer main window form
Let us see some insights of Qt Designer. From Figure 1.10, we can see that there is an open dialog box with title as New Form, prompting the user to select any of the templates/forms or widgets on launching the designer. The widgets selection is shown in Figure 1.11:
Figure 1.11: Qt Designer main window form with widgets
The pre-defined templates present in Qt Designer are as follows:
Dialog with Buttons Bottom: Using this template, a GUI form will be created with 2 buttons, that is, OK and Cancel at the bottom-right position, as shown in Figure 1.12. The widget present is QDialogButtonBox.
Figure 1.12:Dialog with Buttons Bottom
template
Dialog with Buttons Right: Using this template, a GUI form will be created with presence of two buttons, that is, OK and Cancel, at top-right position, as shown in the following Figure 1.13. The widget present is QDialogButtonBox:
Figure 1.13:Dialog with Buttons Right
template
Dialog without Buttons: Using this template, an empty GUI form will be created with superclass as QDialog, where the user can place widgets and create applications as per their own requirement.
Main Window: Using this template, the main application GUI form will be created with superclass as QMainWindow, along with the presence of menubar and toolbar for the user. The user may use it or may delete it as per the need.
Widget: Using this template, an empty GUI form will be created with superclass as QWidget.
These QDialog , QMainWindow and QWidget classes have their own importance.
Suppose there is a requirement to create a GUI form by choosing dialog template. In that case, all the widgets used will be inherited from the superclass QDialog.
Suppose there is a requirement to create a GUI form by choosing main window template. Then, all the widgets used will be inherited from the superclass QMainWindow.
Suppose there is a requirement to create a GUI form by choosing widget template. Here, all the widgets used will be inherited from the superclass QWidget.
Moreover, the screen size is selected as Default size, as shown in Figure 1.14. We can select the screen size from the list of items mentioned in the combobox:
Figure 1.14: Screen size selection
Components of Qt Designer
We will see all the components inside Qt Designer in a nutshell now. There are some numbers present across each arrow mark in Figure 1.15. We will be discussing them one by one:
Figure 1.15: Qt Designer tool
Here are the different numerically marked components:
Menubar: The first thing which we noticed at the top will be nothing but the menubar of Qt Designer for GUI managing. It has File, Edit, Form View, Settings, Window, and the Help options, for interacting with the user.
Toolbar: What we can manage using Menubar can also be replicated using Toolbar. The icons are placed instead of text for user interaction. It provides shortcut icons for most useful functions. There are options like Edit Widgets, Edit Signals/Slots, Edit Buddies and Edit Tab order, in this toolbar of Qt Designer. We will be using all these features with demonstration of some examples.
Widget Box: This is one of the most important areas of Qt Designer. It is located on the left side of Qt Designer window. There is a list of widgets and layouts which provides flexibility to create wonderful GUI forms, and you can access it by using the drag and drop to any location of our GUI. We will study about all these widgets and layouts in detail.
Object Inspector (OI): OI is located on the right side of Qt Designer window, which displays the list of objects used in the form along with their layout display in hierarchical manner.
Property Editor: Under OI, there is a Property Editor dock widget. In this dock widget, we can change the property of a widget, layout or of a window as per our