Who this book is for This book is for the intermediate Python programmer who wants to dig deep into the PyQt application framework and learn how to make powerful GUI applications. It is assumed that the reader knows the basics of Python syntax, features, and idioms such as functions, classes, and common standard library tools. It is also assumed the reader has an environment in which they are comfortable writing and executing Python code. This book does not assume any prior knowledge of GUI development, other GUI toolkits, or other versions of PyQt. ~~~~~~~~~ What this book covers Chapter 1, Getting Started with PyQt, introduces you to the Qt and PyQt libraries. You will learn how to set up your system for writing PyQt applications and be introduced to Qt Designer. You will also write the traditional Hello World application and develop a basic template for PyQt apps. Chapter 2, Building Forms with QtWidgets, shows you the basics of making a PyQt GUI. You'll meet the most common input and display widgets, learn to arrange them using layouts, and learn how to validate user input. You'll put these skills into action developing a calendar GUI. Chapter 3, Handling Events with Signals and Slots, focuses on PyQt's event handling and object communication system. You'll learn how to use this system to make your application respond to user input, and how to create custom signals and slots. You'll put these skills to work by completing your calendar application. Chapter 4, Building Applications with QMainWindow, introduces you to the QMainWindow class, which forms the basis of our applications throughout the rest of the book. You'll also explore PyQt's standard dialog classes and the QSettings module for saving your app's configuration. Chapter 5, Creating Data Interfaces with Model-View Classes, focuses on Qt's Model-View classes. You'll learn the principles of model-view design, explore the model-view classes in QtWidgets, and exercise your knowledge as we develop a CSV editor. Chapter 6, Styling Qt Applications, explores the styling capabilities of PyQt widgets. You will spice up your GUI applications with custom fonts, images, and icons. You'll learn to customize colors using style objects and Qt style sheets. Finally, we'll learn how to do basic animations of style properties. Chapter 7, Working with Audio-Visual Using QtMultimedia, explores the multimedia features of Qt. You will learn how to playback and record audio and video in a way that works seamlessly across platforms. Chapter 8, Networking with QtNetwork, is focused on simple network communications using the QtNetwork library. You will learn to communicate over raw sockets, both Transmission Control Protocol (TCP) and User Datagram Protocol (UDP), as well as learning to transmit and receive files and data using HTTP. Chapter 9, Exploring SQL with QtSQL, introduces you to the world of SQL database programming. You will learn the basics of SQL and the SQLite database. You will then learn how your PyQt applications can use the QtSQL library to access data using raw SQL commands or Qt's SQL model-view classes. Chapter 10, Multithreading with QTimer and QThread, addresses the world of multithreaded and asynchronous programming. You will learn to use timers to delay tasks on the event loop and learn how to push processes into a separate execution thread using QThread. You'll also learn how to do high-concurrency programming using QThreadPool. Chapter 11, Creating Rich Text with QTextDocument, explores rich text and document preparation in Qt. You'll be introduced to Qt's rich text markup language, and learn how to build documents programmatically using QTextDocument. You'll also learn how to use Qt's printing libraries to enable document printing easily across platforms. Chapter 12, Creating 2D Graphics with Qpainter, digs deep into two-dimensional graphics in Qt. You'll learn how to load and edit images and to create custom widgets. You'll also learn about drawing and animating with the Qt Graphics system, and create an arcade-style game. Chapter 13, Creating 3D Graphics with QtOpenGL, introduces you to 3D graphics with OpenGL. You will learn the basics of modern OpenGL programming, and how to use PyQt widgets to display and interact with OpenGL drawings. Chapter 14, Embedding Data Plots with QtCharts, explores Qt's built-in charting capabilities. You'll learn how to create both static and animated charts, and how to customize the colors, fonts, and styles of your charts. Chapter 15, PyQt Raspberry Pi, focuses on the use of PyQt on the Raspberry Pi computer. You'll learn how to set up PyQt on Raspbian Linux, and how to combine the power of PyQt with the Raspberry Pi's GPIO pins to create GUI applications that interact with real-world circuitry. Chapter 16, Web Browsing with QtWebEngine, looks at PyQt's Chromium-based web browser module. You'll explore the capabilities of this module as you build your own multi-tabbed web browser. Chapter 17, Preparing your Software for Distribution, discusses various ways to prepare your code for sharing and distribution. We'll look at optimal project layout, packaging your source code for other Python users using setuptools, and building standalone executables using PyInstaller. Appendix A, Answers to Questions, contains answers or suggestions for the questions at the end of each chapter. Appendix B, Upgrading Raspbian 9 to Raspbian 10, explains how to upgrade a Raspberry Pi device from Raspbian 9 to Raspbian 10, for readers who are trying to follow the book before the official release of Raspbian 10. 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 Code in action Conventions used Get in touch Reviews Section 1: Deep Dive into PyQt Getting Started with PyQt Technical requirements Installing Qt Designer Introducing Qt and PyQt PyQt5 Working with Qt and PyQt Understanding Qt's documentation Core Qt modules Creating Hello Qt – our first window Creating a PyQt application template Introducing Qt Designer Using Qt Designer Summary Questions Further reading Building Forms with QtWidgets Technical requirements Creating basic QtWidgets widgets QWidget QWidget as a top-level window QLabel QLineEdit QPushButton and other buttons QComboBox QSpinBox QDateTimeEdit QTextEdit Placing and arranging widgets Layout classes QHBoxLayout and QVBoxLayout QGridLayout QFormLayout Controlling widget size Container widgets QTabWidget QGroupBox Validating widgets Creating an IPv4 entry widget Using QSpinBox for discrete values Building a calendar application GUI Building the GUI in code Creating the widgets Building the layout Building the GUI in Qt Designer First steps Building the right panel Building the event form Previewing the form Summary Questions Further reading Handling Events with Signals and Slots Technical requirements Signal and slot basics Restrictions on signal and slot connections Creating custom signals and slots Sharing data between windows using custom signals Overloading signals and slots Automating our calendar form Using our hand-coded form Creating and connecting our callback methods The populate _list () method The populate _form () method The save _event () method The delete _event () method The check _delete _btn () method Building our new category pop-up form Using Qt Designer .ui files Connecting slots in Qt Designer Converting .ui files to Python Automatic signal and slot connections Using .ui files without conversion Summary Questions Further reading Building Applications with QMainWindow Technical requirements The QMainWindow class Setting a central widget Adding a status bar Creating an application menu Menus on macOS Adding toolbars Adding dock widgets Other QMainWindow features Standard dialog boxes QMessageBox QFileDialog QFontDialog Other dialog boxes Saving settings with QSettings Limitations of QSettings Summary Questions Further reading Creating Data Interfaces with Model-View Classes Technical requirements Understanding model-view design Models and views in PyQt Building a CSV editor Creating a table model Implementing read capabilities Adding headers and sorting Implementing write capabilities Using the model in a view Summary Questions Further reading Styling Qt Applications Technical requirements Using fonts, images, and icons Setting a font Dealing with missing fonts Adding images Using icons Using Qt resource files Qt resource files and fonts Configuring colors, style sheets, and styles Customizing colors with palettes Working with QBrush objects Customizing the appearance with Qt Style Sheets (QSS) The downside of QSS Customizing the appearance with QStyle Customizing Qt styles Drawing widgets Creating animations Basic property animations Animating colors Using animation groups Summary Questions Further reading Section 2: Working with External Resources Working with Audio-Visual Using QtMultimedia Technical requirements Simple audio playback Recording and playing audio The initial setup Implementing sound playback Loading the media Tracking the playback position Looping the audio Setting the volume Implementing recording Examining and configuring the recorder Recording and playing video Building the basic GUI Video playback Video recording Summary Questions Further reading Networking with QtNetwork Technical requirements Low-level networking with sockets Building a chat GUI Building a UDP chat client Connecting signals Testing the chat Building a TCP chat client Working with data streams Sending data over TCP Connecting our backend and testing HTTP communications with QNetworkAccessManager Simple downloading Posting data and files Building the GUI The POSTing backend Testing the utility Summary Questions Further reading Exploring SQL with Qt SQL Technical requirements SQL basics Creating tables Inserting and updating data Updating existing rows Selecting data Table joins SQL subqueries Learning more Performing SQL queries with Qt Building a form Connecting and making simple queries Getting information about the database Making simple queries Prepared queries Using QSqlQueryModel Finishing the GUI Using model-view widgets without SQL Delegates and data mapping Data mapping Filtering data Using a custom delegate Inserting custom rows in a table view Summary Questions Further reading Section 3: Unraveling Advanced Qt Implementations Multithreading with QTimer and QThread Technical requirements Delayed actions with QTimer Single shot timers Repeating timers Getting information from timers Limitations of timers Multithreading with QThread The SlowSearcher file search engine A non-threaded searcher Testing our non-threaded search application Adding threads An alternate method Threading tips and caveats High concurrency with QThreadPool and QRunner The file hasher GUI A hash runner Creating the thread pool Testing the script Threading and the Python GIL Summary Questions Further reading Creating Rich Text with QTextDocument Technical requirements Creating rich text using markup HTML basics Style sheet syntax Semantic versus cosmetic tags Structure and heading tags Typography tags Hyperlinks Lists and tables Fonts, colors, images, and styles Document-wide styles Images Differences between Qt rich text and Web HTML Manipulating rich text using QTextDocument Creating the invoice application GUI Building InvoiceView The QTextDocument structure Character formats Adding basic content Inserting a list Inserting a table Finishing and testing Printing rich text Updating the Invoice app for print support Configuring the printer Printing a page Print previewing Exporting to PDF Summary Questions Further reading Creating 2D Graphics with QPainter Technical requirements Image editing with QPainter The meme generator GUI The editing form The main GUI Drawing with QImage The QPainter object Saving our image Custom widgets with QPainter Building a GraphWidget Painting the widget Using GraphWidget Animating 2D graphics with QGraphicsScene First steps Making a scene Creating the tanks Creating the bullets Collision detection Finishing the game Summary Questions Further reading Creating 3D Graphics with QtOpenGL Technical requirements The basics of OpenGL The rendering pipeline and drawing basics Programs and shaders A simple vertex shader A simple fragment shader Embedding OpenGL drawings with QOpenGLWidget First steps with OpenGLWidget Creating a program Accessing our variables Configuring a projection matrix Drawing our first shape Creating a 3D object Animating and controlling OpenGL drawings Animating in OpenGL Zooming in and out Summary Questions Further reading Embedding Data Plots with QtCharts Technical requirements Making a simple chart Setting up the GUI Building a disk usage chart Displaying real-time data Building a CPU usage chart Updating the chart data Panning and zooming around the chart Styling Qt charts Building the memory chart Chart styling Styling axes Styling the legend Summary Questions Further reading PyQt Raspberry Pi Technical requirements Running PyQt5 on the Pi Editing Python on the Pi Running PyQt5 applications on the Pi Controlling GPIO devices with PyQt Connecting the LED circuit Writing a driver library PWM Setting a color Cleaning up Creating the PyQt GUI Controlling PyQt with GPIO devices Connecting the sensor circuit Creating the sensor interface Displaying the readings Adding a hardware button Expanding the circuit Implementing the button driver Summary Questions Further reading Web Browsing with QtWebEngine Technical requirements Building a basic browser with QWebEngineView Using the QWebEngineView widget Allowing multiple windows and tabs Adding a tab for pop-up windows Advanced QtWebEngine usage Sharing a profile Viewing history Web settings Building a text search feature Summary Questions Further reading Preparing Your Software for Distribution Technical requirements Structuring a project Tic-tac-toe The engine class The board class The main window class Module-style structure Structuring the module Non-Python files Documentation and metadata The LICENSE file The README file The docs directory The requirements.txt file Other files Distributing with setuptools Writing the setuptools configuration Basic metadata arguments Packages and dependencies Non-Python files Executables Source distributions Creating a source distribution Installing a source distribution Built distributions Types of built distributions Creating a wheel distribution Installing a built distribution Compiling with PyInstaller PyInstaller overview Basic command-line usage The .spec file Preparing QTicTacToe for PyInstaller Dealing with non-Python files Further debugging Summary Questions Further reading Answers to Questions Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Upgrading Raspbian 9 to Raspbian 10 Other Books You May Enjoy Leave a review - let other readers know what you think An advanced guide to creating powerful high-performance GUIs for modern, media-rich applications in various domains such as business and game development Key FeaturesGain comprehensive knowledge of Python GUI development using PyQt 5.12Explore advanced topics including multithreaded programming, 3D animation, and SQL databasesBuild cross-platform GUIs for Windows, macOS, Linux, and Raspberry PiBook DescriptionPyQt5 has long been the most powerful and comprehensive GUI framework available for Python, yet there is a lack of cohesive resources available for Python programmers to learn how to use it. This book will be your comprehensive guide to exploring GUI development with PyQt5. You will get started with an introduction to PyQt5, before going on to develop stunning GUIs with modern features. You will learn how to build forms using QWidgets and delve into important aspects of GUI development such as layouts, size policies, and event-driven programming. Moving ahead, youll discover PyQt5s most powerful features through chapters on audio-visual programming with QtMultimedia, database-driven software with QtSQL, and web browsing with QtWebEngine. Next, in-depth coverage of multithreading and asynchronous programming will help you run tasks asynchronously and build high-concurrency processes with ease. In later chapters, youll gain insights into QOpenGLWidget, along with mastering techniques for creating 2D graphics with QPainter. Youll also explore PyQt on a Raspberry Pi and interface it with remote systems using QtNetwork. Finally, you will learn how to distribute your applications using setuptools and PyInstaller. By the end of this book, you will have the skills you need to develop robust GUI applications using PyQt. What you will learnGet to grips with the inner workings of PyQt5Understand how elements in a GUI application communicate with signals and slotsStudy techniques for styling an applicationExplore database-driven applications with the QtSQL moduleCreate 2D graphics with QPainterDelve into 3D graphics with QOpenGLWidgetBuild network and web-aware applications with QtNetwork and QtWebEngineWho this book is forThis book is for programmers who want to create attractive, functional, and powerful GUIs using the Python language. Youll also find this book useful if you are a student, professional, or anyone who wants to start exploring GUIs. Although prior knowledge of the Python language is assumed, experience with PyQt, Qt, or GUI programming is not required. Table of ContentsGetting Started with PyQtBuilding Forms with QtWidgetsHandling events with signals and slotsBuilding applications with QMainWindowCreating data interfaces with Model/View classesStyling Qt ApplicationsWorking with Audio-visual Using QtMultimediaNetworking with QtNetworkExploring SQL with QtSQLMultithreading with QTimer and QthreadCreating Rich text with QTextDocumentCreating 2D graphics with QpainterCreating 3D graphics with QtOpenGLEmbedding data plots with QtCharts PyQt Raspberry PiWeb browsing with QtWebEnginePreparing Your Software for DistributionAppendix Answers to Questions