© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
J. M. WillmanBeginning PyQthttps://doi.org/10.1007/978-1-4842-7999-1_1

1. Getting Started with PyQt

Joshua M Willman1  
(1)
Sunnyvale, CA, USA
 

Hello! Welcome to Beginning PyQt: A Hands-on Approach to GUI Programming. You are probably here because you would like to learn how to build applications and need some help getting started. Maybe you have a personal program you need to build, or perhaps you would like to build a custom software application for others to use. Whatever your reason may be, you’ll need to figure out where is the best place to start.

The goal of this book is to take a practical approach to coding user interfaces. You’ll be able to follow along and code numerous examples, both simple and complex. You’ll also gain knowledge through visualization and practice that show how to use fundamental concepts you need to build your own applications. In many cases, those concepts will then be applied to larger projects.

In this chapter, you will
  • Learn about the PyQt toolkit for creating user interfaces

  • Set up Python 3 and download the latest version of PyQt6

  • Consider some fundamental concepts for building user-friendly interfaces

  • Create your first application with PyQt

Let’s begin this journey by finding out more about PyQt.

The PyQt Framework

The PyQt toolkit is a set of Python bindings for the Qt cross-platform widget toolkit and application framework. What does that mean?

First, Qt is used for the development of user interfaces and other applications and is being developed by The Qt Company. The framework is significant because it can run on numerous software and hardware systems such as Windows, macOS, Linux, Android, or embedded systems with little to no change to the underlying code and is still able to maintain capabilities and speed of the system on which it is being run. So in general, you’ll be able to make some amazing cross-platform applications without having to worry about the user’s platform.

Second, this all means that PyQt combines all the advantages of the Qt C++ cross-platform widget toolkit with Python, the powerful and simple, cross-platform interpreted language. It’s worth noting that while PyQt has its own documentation, the Qt documentation tends to be more complete. If you have never used C++ before, this can seem like a daunting task. We’ll discuss this topic a little further in this chapter’s first application.

For more information about Qt, have a look at www.qt.io.

For more information about PyQt, check out www.riverbankcomputing.com/news.

Why Choose PyQt?

PyQt is capable of more than just creating graphical interfaces, as it also has access to Qt classes that cover mechanics such as XML handling, SQL databases, network communication, graphics and animations, and many other technologies. Take the capabilities of Qt and combine them with the number of extension modules that Python provides and you have the ability to create new applications that can build upon these preexisting libraries.

PyQt also includes Qt Designer, which allows for anyone to assemble a GUI much faster using a simple drag-and-drop graphical interface designer. Qt Designer is discussed in detail in Chapter 8.

Using PyQt’s signal and slot mechanism, you can create an extremely interactive interface and customize how different PyQt components interact. This will be covered in more detail in Chapters 3 and 7.

There are, of course, other toolkits available for creating applications with GUIs using Python, such as Tkinter, wxPython, and PySide, and they all have their own advantages. For example, Tkinter comes bundled with Python, meaning that you can find an abundance of helpful resources by doing a quick search on the Internet. PySide is the Python binding of Qt managed by The Qt Company itself. Despite this, PyQt still has a larger following thanks to its age and awesome community of developers.

It is worth noting that if you choose to use PyQt to create commercial applications, you will need to get a license. Applications created in this book will leverage the GNU General Public License (GPL) .

Ultimately, it all comes down to choosing the toolkit that works the best for your project.

PyQt5 vs. PyQt6

The latest version of Qt has brought more focus on 2D and 3D capabilities. There are also quite a few changes in the latest version of PyQt . Since this book’s aim is to introduce the fundamentals of developing applications with PyQt, we will take a look at the changes that will impact you the most at this stage of your journey:
  • As you dive more into PyQt, you’ll definitely use enums, flags, and other identifiers in the Qt Namespace. They are useful for setting the properties of the different classes in PyQt. What’s important to understand now is that the fully qualified names are now used for these items rather than the shorthand ones used in PyQt5. For example, PyQt5 used Qt.AlignCenter to center text, but PyQt6 uses the full name, Qt.AlignmentFlag.Center. You will see numerous examples of this throughout the book, and we’ll discuss this more in later chapters.

  • Some classes and methods have been deprecated, such as QDesktopWidget, while others have been moved, such as the QAction class is now located in the QtGui module.

  • The exec() method is now used in PyQt6 to start the event loop of your application rather than exec_().

This is not an exhaustive list, and you will find out more about these and other topics as you follow along. If you are interested to see more of the new changes in PyQt6, have a look at www.riverbankcomputing.com/static/Docs/PyQt6/pyqt5_differences.html.

Installing Python 3 and PyQt6

So that all readers are on the same page, let’s begin by installing or updating your version of Python.

Checking Your Version of Python

In order to use PyQt, you will first need to have Python 3.7 or higher installed.

Note

When PyQt6 was first released, it was compatible with Python 3.6.1 or higher. However, that was scheduled to be discontinued at some point in the future. You should have Python 3.7 or higher on your system just to be on the safe side.

To check which version of Python 3 you have installed on your system, open your system’s shell, and run the command
$ python3 --version

Change python3 to python on Windows. This will return your system’s Python 3 version. If yours happens to be lower than Python 3.7 or you don’t have Python installed, then have a look at www.python.org/downloads/ to get the latest version.

Tip

For those readers that might not want to remove their current version of Python and would like to manage multiple Python versions on their system, have a look at the Python version management tool, pyenv.

Installing PyQt6

Since PyQt does not come included with your Python installation, the next step is to use pip to install the PyQt6 package from the Python Package Index (PyPI) . To create the bindings between Python and C++, the SIP binding generator tool is used. When downloading PyQt6 from PyPI, the sip module will automatically be downloaded too.

To install PyQt6, enter the following command into your shell:
$ pip3 install PyQt6
If you are using Windows, you will probably need to change pip3 to pip. To make sure PyQt is downloaded properly, open up the Python 3 interpreter by entering python3 (python for Windows) into the command line. Then enter the following command:
>>> import PyQt6
Tip

Throughout the course of this book, you’ll create a number of PyQt GUIs. For those readers who are interested in managing their different PyQt projects and their dependencies, have a look at using virtual environments and the Python module, venv.

If no errors are returned, we can now move on and learn a little bit more about user interfaces.

Introduction to User Interfaces

The user interface (UI) has become a key part of our everyday lives, becoming the intermediary between us and our ever-growing number of machines. A UI is designed to facilitate in human-computer interaction. The human needs to operate and control the machine to serve some purpose; meanwhile, the machine needs to simultaneously provide feedback and a means to interact with it in order to aid the human’s decision-making process. UIs are everywhere, from the mobile applications on our phones to web browsers, to heavy machinery controls, and even on the appliances in our kitchens. Of course, the ways in which we interact with technology is not merely limited to our hands, as many UIs also allow interaction with our other sensory organs.

A good UI is tasked with helping a person produce a desired result while also allowing for easier, more efficient, and more friendly operation of a machine. Think about the photo editing apps on your phone. Editing the size, color, or exposure is practically effortless as you slide your fingers across the screen and watch the images change almost instantly. The user provides minimal input to achieve the desired output.

What Is a Graphical User Interface?

For this book, we will be focusing on creating desktop graphical user interfaces (GUI) that take advantage of a computer’s graphics capabilities to create visual applications. Decades ago, users would have to use the command line and text commands to interact with the computer. Tasks such as opening, deleting and moving files, and searching through directories were all done by typing in certain commands. However, these were not very user-friendly or simple-to-use interfaces for the general public. So GUIs were created to allow users to interact with electronic devices using graphical controls, rather than command-line interfaces.

These graphical control elements, or widgets, such as buttons, menus, and windows, make such tasks effortless. Interaction now becomes as simple as moving your mouse or touching the screen depending upon your device and clicking on the widget.

Concepts for Creating Good Interface Design

This, first and foremost, is a technical book written to help those of you who want to learn how to create and code your own GUI with PyQt and Python. That being said, if you plan to design any kind of UI that other people will use, then you are no longer creating a UI just to solve your own problems. You must also begin to consider other users of the application as well. Think about what you want them to accomplish, or how the application can help them. Sometimes, when we are trying to solve a problem, we get so caught up in trying to create a product that we forget about the people who actually have to interact with them.

The following is a list of concepts to consider when designing your own UI. They are not set rules and by no means a complete list, but rather ideas that you should consider when designing your own applications.
  1. 1.

    Clarity – Using clear language, hierarchy, and flow with visual elements to avoid ambiguity. One of the ways this can be achieved is by considering visual importance to the human eye, laying out widgets with bigger sizes, darker colors, etc., in such a manner that we can visually understand the UI.

     
  2. 2.

    Conciseness – Simplifying the layout to include only what the user needs to see or interact with at a given time in order to be brief, but also comprehensive. Adding more labels or buttons in your window just to give the user more options is not always better.

     
  3. 3.

    Consistency – Design the UI so that there is consistency across the application. This helps users to recognize patterns in the visual elements and layout and can be seen in typography that improves the navigation and readability of the application, image styles, or even color schemes.

     
  4. 4.

    Efficiency – Utilizing good design and shortcuts to help the user improve productivity. If a task can be accomplished in two steps, why design your GUI so that the work has to be completed in five?

     
  5. 5.

    Familiarity – Consider elements that users normally see in other UIs and how they would expect them to perform in your applications. For example, think about how weird it would be to have to enter your login information, only to find the password entry field is above the username. It is not wrong, but now you are unnecessarily making users think about their actions and slowing them down.

     
  6. 6.

    Responsive – Give the user feedback, for example, a toggle that changes color to “on” or “off,” a small message to notify the user if their input is correct or incorrect, or even a sound effect to verify a completed action. The user should never be left wondering if their action was successful or not.

     

Creating Your First GUI: An Empty Window

A GUI application generally consists of a main window and possibly one or more dialog boxes. The main window is where the user will spend most of their time when using your application and can consist of a menu bar, a status bar, and other widgets. Dialog boxes typically are made up of text, maybe one or more widgets for collecting information, and buttons. They appear to the user when necessary to communicate information and prompt them for input. An alert window that pops up asking you if you want to save changes to your document is an example of a dialog. Dialog boxes will be covered further in Chapter 3.

For your first project, seen in Figure 1-1, we’ll consider
  • How to create an empty window in PyQt6

  • The basic classes and modules needed to set up your GUI

  • How to modify the main window’s size and title

Figure 1-1

Empty window created with PyQt6

This application will serve as the foundation for all other programs found in this book.

Explanation for Creating an Empty Window

The code found in Listing 1-1 is all you need to create a window in PyQt6. Examples throughout this book will take advantage of object-oriented programming (OOP) , a programming paradigm that focuses on using classes to create instances of those classes, or objects, with their own properties and behaviors and modeling the relationships between other objects.
# basic_window.py
# Import necessary modules
import sys
from PyQt6.QtWidgets import QApplication, QWidget
class EmptyWindow(QWidget):
    def __init__(self):
        """ Constructor for Empty Window Class """
        super().__init__()
        self.initializeUI()
    def initializeUI(self):
        """Set up the application."""
        self.setGeometry(200, 100, 400, 300)
        self.setWindowTitle("Empty Window in PyQt")
        self.show() # Display the window on the screen
# Run the program
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = EmptyWindow()
    sys.exit(app.exec())
Listing 1-1

Creating an empty window in PyQt

Your initial window should look similar to the one in Figure 1-1 depending upon your operating system.

Walking through the code, we first start by importing the sys and PyQt6 modules that we need to create a window. The sys module can be used in PyQt to pass command line arguments to our applications and to close them.

The QtWidgets module provides the widget classes that you will need to create desktop-style GUIs. From the QtWidgets module, we import two classes: QApplication and QWidget. You only need to create a single instance of the QApplication class, no matter how many windows or dialog boxes exist in an application. QApplication is responsible for managing the application’s main event loop and widget initialization and finalization. The main event loop is where user interactions in the GUI window, such as clicking on a button, are managed. Take a quick look at
    app = QApplication(sys.argv)
QApplication takes as an argument sys.argv. You can also pass in an empty list if you know that your program will not be taking any command line arguments using
    app = QApplication([])
Tip

Always create your GUI’s QApplication object before any other object belonging to the GUI, including the main window. This concept is demonstrated in Listing 1-2.

Next, we create a window object that inherits from the class we created, EmptyWindow. Our class actually inherits from QWidget, which is the base class for which all other user interface objects, such as widgets and windows, are derived.

Tip

When creating windows in PyQt, you will generally create a main class that inherits from either QMainWindow, QWidget, or QDialog. You’ll find out more about each of these classes and when to use them to create windows and dialog boxes in later chapters.

We need to call the show() method on the window object to display it to the screen. This is located inside the initializeUI() function in our EmptyWindow class. You can see app.exec() being passed as an argument to sys.exit() in the final line of Listing 1-1. The method exec() starts the application’s event loop and will remain here until you quit the application. The function sys.exit() ensures a clean exit.

The steps for creating a window are better illustrated in Listing 1-2 using procedural programming , a programming paradigm where the computer follows a set of sequential commands to perform a task.
# procedural.py
# 1. Import necessary modules
import sys # use sys to accept command line arguments
from PyQt6.QtWidgets import QApplication, QWidget
app = QApplication(sys.argv) # 2. Create QApplication object
window = QWidget() # 3. Create window from QWidget object
window.show() # 4. Call show to display GUI window
# 5. Start the event loop. Use sys.exit to close the program
sys.exit(app.exec())
Listing 1-2

Minimum code needed for creating an empty window in PyQt without OOP

The next section demonstrates how to use built-in PyQt methods to change the main window’s size and set the window’s title.

Modifying the Window

The EmptyWindow class in Listing 1-1 contains a method, initializeUI(), that creates the window based upon the parameters we specify. The initializeUI() function is reproduced in the following code snippet:
    def initializeUI(self):
        """Initialize the window and display its contents to
        the screen."""
        self.setGeometry(200, 100, 400, 300)
        self.setWindowTitle('Empty Window in PyQt')
        self.show()

The method setGeometry() defines the location of the window on your computer screen and its dimensions, width and height. So the window we just created is located at x=200, y=100 in the window and has width=400 and height=300. The setWindowTitle() method is used to set the title of the window. Take a moment to modify the geometry values or title text and see how your changes affect the window. You could also comment out the two methods and see how PyQt uses default parameter settings for both the size and window title.

We will look at further customization of the window’s layout in Chapter 4 and appearance in Chapter 6.

Summary

In this chapter, we took a look at getting you set up to build GUIs using PyQt6. Creating user-friendly GUIs is important, and there are a few notions you should keep in mind when designing your applications, such as consistency and clarity, to help users understand your application’s purpose and features. Finally, we took a look at the basic classes and methods needed for creating and modifying a simple main window.

In the next chapter, you will learn more about GUI development. You’ll find out how to add text and images to GUIs using the widget QLabel while also learning one method for arranging widgets in your windows.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset