Mastering GUI Programming with Python - Alan D. Moore - E-Book

Mastering GUI Programming with Python E-Book

Alan D Moore

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

An advanced guide to creating powerful high-performance GUIs for modern, media-rich applications in various domains such as business and game development


Key Features:


Gain 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 Pi


Book Description:


PyQt5 has long been the most powerful and comprehensive GUI framework available for Python, yet there is a lack of cohesive resources available to teach Python programmers how to use it. This book aims to remedy the problem by providing comprehensive coverage of 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 then learn how to build forms using QWidgets and learn about important aspects of GUI development such as layouts, size policies, and event-driven programming. Moving ahead, you’ll discover PyQt5’s 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, you’ll gain insights into QOpenGLWidget, along with mastering techniques for creating 2D graphics with QPainter. You’ll 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 learn:


Get to grips with the inner workings of PyQt5Learn how elements in a GUI application communicate with signals and slotsLearn 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 QtWebEngine


Who this book is for:


This book is for programmers who want to create attractive, functional, and powerful GUIs using the Python language. You’ll also find this book useful if you are a student, professional, or anyone who wants to start exploring GUIs or take your skills to the next level. Although prior knowledge of the Python language is assumed, experience with PyQt, Qt, or GUI programming is not required.


Alan D. Moore is a data analyst and software developer who has been solving problems with Python since 2006. He's developed both open source and private code using frameworks like Django, Flask, Qt, and, Tkinter, and contributes to various open source Python and Javascript projects. Alan is the author of Python GUI Programming with Tkinter.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 629

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering GUI Programming with Python

 

Develop impressive cross-platform GUI applications with PyQt

 

 

 

 

 

 

 

 

 

Alan D. Moore

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Mastering GUI Programming with Python

Copyright © 2019 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:Shriram ShekharContent Development Editor:Digvijay BagulTechnical Editor:Abin SebastianCopy Editor: Safis EditingProject Coordinator:Prajakta NaikProofreader: Safis EditingIndexer:Pratik ShirodkarGraphics Coordinator:Jisha ChirayilProduction Coordinator:Aparna Bhagat

First published: May 2019

Production reference: 1230519

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78961-290-5

www.packtpub.com

To my children—may you be inspired to create, be diligent to create well, and be bold enough to share your creations confidently with the world.
– Alan D. Moore
 
mapt.io

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.

Why subscribe?

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

Packt.com

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.packt.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.packt.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. 

Contributors

About the author

Alan D. Moore is a data analyst and software developer who has been solving problems with Python since 2006. He's developed both open source and private code using frameworks such as Django, Flask, Qt, and Tkinter, and contributes to various open source Python and JavaScript projects. Alan is the author of Python GUI Programming with Tkinter.

 

About the reviewer

Chankey Pathak is a data scientist from India. He's the author of a Python API for high-frequency trading with Morgan Stanley. He has worked with Citadel, Sophos, and Proofpoint in the past. He's also well-known in the Perl community for his contributions. He is an open source contributor and loves Linux.

 

 

 

 

 

Packt is searching for authors like you

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.

Table of Contents

Title Page

Copyright and Credits

Mastering GUI Programming with Python

Dedication

About Packt

Why subscribe?

Packt.com

Contributors

About the author

About the reviewer

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

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

Preface

In an age when the term application developer nearly always implies web application developer, the building of desktop GUI applications may seem in danger of becoming a quaint and obscure art. Yet on every forum, mailing list, and chat service where programming is discussed, I find young Python coders eager to dive into GUI toolkits so that they can start building the kind of software that any average person can readily identify as an application. The one GUI library consistently recommended to these learners, the one that is arguably Python's most exciting and most complete toolkit, is PyQt.

Despite this popularity, there have been relatively few resources available for learning PyQt. Those who wish to learn it must rely heavily on outdated books, C++ documentation, scattered blogs, or snippets of code found in mailing lists or Stack Overflow posts. There is an apparent need for a modern tutorial and reference on PyQt for the Python programmer, and this book aims to fill that need.

My first book, Python GUI Programming with Tkinter, focused on the rudiments of application development using Tkinter, covering core topics such as interface design, unit testing, program architecture, and packaging. In this book, I wanted to go beyond the basics, not just teaching you how to build data-driven business forms (which so many toolkits can produce, and so many other books can teach you to write), but to explore the more exciting and unique possibilities offered by PyQt: multimedia, animation, 3D graphics, image manipulation, networking, multi-threading, and more. Of course, this book doesn't shirk the business side of things either, with solid coverage of data entry forms, SQL databases, and charting.

There are two kinds of authors who write technical books. The first is the absolute expert, with infallible authority and encyclopedic knowledge of the topic at hand, who is able to draw on a deep understanding to produce explanations that perfectly address the learner's most pertinent needs.

The second kind of author is a mere mortal possessed of a reasonable familiarity with the basics, a willingness to research what is not known, and most importantly, a dogged determination to ensure that every statement asserted in print is the whole and correct truth. This author must be prepared to stop mid-sentence in the flow of writing to test claims in the interpreter or code editor; to spend hours reading documentation, mailing-list threads, code comments, and IRC logs in the pursuit of a more correct understanding; and to delete and rewrite large swathes of their work when a new fact reveals a fault in their original assumptions.

When I was asked to write a book on PyQt5, I could make no claims to being the first sort of author (nor can I now); while I had developed and maintained several PyQt applications both at work and in the open source world, my understanding of PyQt rarely strayed beyond the simple needs of my own code. So, I have aspired to be the second type, committing myself to diligent study and the painstaking process of sifting and distilling the tangled mass of available information into a text that might guide the aspiring GUI programmer toward mastery of PyQt.

As a proud father of five children, some of whom have a budding (if not blooming) interest in programming, I have worked these past six months to write a book that I could confidently and conscientiously put before them, should they wish to learn these skills. I hope, dear reader, that you sense in this text this parental enthusiasm for your growth and progress as we tackle this subject together.

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.

To get the most out of this book

The reader is expected to have proficiency in the Python language, particularly Python 3. You should understand, at least in a basic sense, how to work with classes and object-oriented programming. You may find it helpful to have a passing familiarity with C++, since most of the available Qt documentation is aimed at that language.

You should have a computer running Windows, macOS, or Linux on which Python 3.7 has been installed, and on which you can install other software as needed. You should have a code editor and command-line shell with which you are comfortable. Finally, you should have access to the internet.

Each chapter of this book contains one or more example applications. Although these examples are available for download, you are encouraged to follow along, creating these applications by hand to see the intermediate stages as the applications come together.

Each chapter also contains a series of questions or a suggested project to cement your knowledge of the topic, and a selection of resources for further study on the topic. You will get the most out of each chapter if you engage your mind and creativity in solving these problems and reading the provided materials.

The code included in this book is released under the open source MIT license, which allows you to re-use the code as you see fit, provided you retain the included copyright notices. You are encouraged to use, modify, improve, and re-publish these programs.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.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.packt.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 at https://github.com/PacktPublishing/Mastering-GUI-Programming-with-Python/tree/master. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/9781789612905_ColorImages.pdf.

Code in action

Visit the following link to check out videos of the code being run: http://bit.ly/2M3QVrl

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "HTML documents are built hierarchically, with the outermost tag usually being <html>."

A block of code is set as follows:

<table border=2> <thead> <tr bgcolor='grey'><th>System</th><th>Graphics</th><th>Sound</th></tr> </thead>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<table border=2> <thead> <tr

bgcolor='grey'

><th>System</th><th>Graphics</th><th>Sound</th></tr> </thead>

Any command-line input or output is written as follows:

$ python game_lobby.py

Font is Totally Nonexistent Font Family XYZ

Actual font used is Bitstream Vera Sans

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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.packt.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.

Reviews

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 packt.com.

Section 1: Deep Dive into PyQt

In this section, you will explore the core features of PyQt. By the end of this section, you should be comfortable with the basic design workflow and coding idioms involved in writing PyQt applications and feel confident in your ability to construct simple PyQt interfaces.

The following chapters are in this section:

Chapter 1

,

Getting Started with PyQt

Chapter 2

,

Building Forms with QtWidgets

Chapter 3

,

Handling Events with Signals and Slots

Chapter 4

,

Building Applications with QMainWindow

Chapter 5

,

Creating Data Interfaces with Model-View Classes

Chapter 6

,

Styling Qt Applications

Getting Started with PyQt

Welcome, Python programmer!

Python is a great language for system administration, data analysis, web services, and command-line programs; most likely you've already found Python useful in at least one of those areas. However, there is something truly satisfying about building the kind of GUI-driven application that an end user can readily identify as a program, and this skill should be in the toolbox of any master software developer. In this book, you're going to learn how you can use Python and the Qt framework to develop amazing applications—from simple data-entry forms to powerful multimedia tools.

We'll start our tour of these powerful technologies with the following topics:

Introducing Qt and PyQt

Creating

Hello Qt

 – our first window

Creating a PyQt application template

Introducing Qt Designer

Technical requirements

For this chapter, and most of the rest of the book, you're going to need the following:

A PC running

Microsoft Windows

,

Apple macOS

, or a 64-bit flavor of

GNU/Linux

.

Python 3

, available from

http://www.python.org

. The code in this book requires Python 3.7 or later.

PyQt 5.12

, which you can install from the Python Package Index using this command:

$ pip install --user PyQt5

Linux users may also wish to install PyQt5 from their distribution's package repositories.

Qt Designer 4.9

, a WYSIWYG GUI building tool available from

https://www.qt.io

. See the following section for installation instructions.

The

example code

from

https://github.com/PacktPublishing/Mastering-GUI-Programming-with-Python/tree/master/Chapter01

.

Check out the following video to see the code in action: http://bit.ly/2M5OUeg

Installing Qt Designer

On Windows or macOS, Qt Designer is part of the Qt Creator IDE from the Qt company. This is a free IDE that you can use for coding, though, at the time of writing, it is mainly aimed at C++ and support for Python is rudimentary. The Qt Designer component can be used regardless of whether you do your coding in Qt Creator or not.

You can download an installer for Qt Creator from https://download.qt.io/official_releases/qtcreator/4.9/4.9.0/.

Although the Qt company offers a similar standalone Qt installer for Linux, most Linux users will prefer to use packages from their distribution's repositories. Some distributions offer Qt Designer as a standalone application, while others include it in their Qt Creator packages.

This table shows the package that will install Qt Designer in several major distributions:

Distribution

Package name

Ubuntu, Debian, Mint

qttools5-dev-tools

Fedora, CentOS, Red Hat, SUSE

qt-creator

Arch, Manjaro, Antergos

qt5-tools

Introducing Qt and PyQt

Qt is a cross-platform application framework that was created for use with C++. Available in both commercial and open source licenses (General Public License (GPL) v3 and Lesser General Public License (LGPL) v3, specifically), it is widely used by open source projects such as KDE Plasma and Oracle VirtualBox, commercial software such as Adobe Photoshop Elements and Autodesk Maya, and even embedded software in products from companies such as LG and Panasonic. Qt is currently owned and maintained by the Qt company (https://www.qt.io).

In this book, we're going to be working with the open source release of Qt 5.12. If you're using Windows, macOS, or a major Linux distribution, you should not need to install Qt explicitly; it will be installed automatically when you install PyQt5.

Qt is officially pronounced cute, though many people say, Q T.

PyQt5

PyQt is a Python library that allows the Qt framework to be used in Python code. It was developed by Riverbank Computing under the GPL license, although commercial licenses can be purchased for those wanting to develop proprietary applications. (Note that this is a separate license from the Qt license.) It is currently supported on Windows, Linux, UNIX, Android, macOS, and iOS.

PyQt's bindings are generated automatically by a tool called SIP, so, to a large extent, working with PyQt is just like working with Qt itself, only in Python. In other words, the classes, methods, and other objects are all identical in usage, apart from the language syntax.

The Qt company has recently released Qt for Python (also known as PySide2), their own Python Qt5 library, under the terms of the LGPL. Qt for Python is functionally equivalent to PyQt5, and code can be ported between them with very few changes. This book will cover PyQt5, but what you learn can easily be applied to Qt for Python, should you need an LGPL library.

Working with Qt and PyQt

Qt is much more than a GUI library; it's an application framework. It contains dozens of modules with thousands of classes. It has classes to wrap simple data types such as dates, times, URLs, or color values. It has GUI components such as buttons, text entries, or dialog boxes. It has interfaces for hardware such as cameras or mobile sensors. It has a networking library, a threading library, and a database library. If anything, Qt is truly a second standard library!

Qt is written in C++ and designed around the needs of C++ programmers; it works well with Python, but Python programmers may find some of its concepts slightly foreign at first.

For example, Qt objects usually expect to work with data wrapped in Qt classes. A method that expects a color value won't accept a string or a tuple of RGB values; it wants a QColor object. A method that returns a size won't return a (width, height) tuple; it will return a QSize object. PyQt mitigates this somewhat by automatically converting some common data types (for example, strings, lists, dates, and times) between Qt objects and Python standard library types; however, there are many hundreds of Qt classes that have no analog in the Python standard library.

Qt relies heavily on named constants called enums or flags to represent things such as option settings or configuration values. For example, if you wanted to switch the state of a window between minimized, floating, or maximized, you would need to pass the window a constant that is found in the QtCore.Qt.WindowState enum.

Setting or retrieving values on Qt objects requires the use of accessor methods, sometimes known as setter and getter methods, rather than direct access to the properties.

To the Python programmer, Qt can seem to have an almost maniacal obsession with defining classes and constants, and you'll spend a lot of time early on searching the documentation to locate the item you need to configure your objects. Don't despair! You'll soon become acclimated to the Qt way of working.

Understanding Qt's documentation

Qt is such a vast and complex library that no print book could hope to document a significant portion of it in any detail. For that reason, it's important to learn how to access and understand the documentation available online. For Python programmers, this presents a minor challenge.

Qt itself is blessed with detailed and excellent documentation that documents all Qt modules and classes, including example code and high-level tutorials on coding with Qt. However, this documentation is all aimed at C++ development; all example code is in C++, and there is no indication when a methodology or approach to a problem differs for Python.

PyQt's documentation is considerably sparser. It only covers the Python-specific differences and lacks the comprehensive class reference, example code, and tutorials that make Qt's documentation great. It is an essential read for anyone working with PyQt, but it's by no means complete.

With the release of Qt for Python, there is an effort underway to port Qt's C++ documentation to Python at https://doc-snapshots.qt.io/qtforpython/. When finished, this will also be a valuable resource for PyQt programmers. At the time of writing, though, the effort is far from complete; in any case, there are minor differences between PyQt and Qt for Python that may make this documentation as confusing as it is helpful.

If you have a rudimentary knowledge of C++ syntax, it's not too difficult to mentally translate the Qt documentation to Python, though it can be confusing in many cases. One of the aims of this book is to close the gap for those who aren't well-versed in C++.

Core Qt modules

For the first six chapters of this book, we'll be working primarily with three Qt modules:

QtCore

, which contains low-level data wrapper classes, utility functions, and non-GUI core functionality

QtGui

, which contains GUI-specific data wrapper classes and utilities

QtWidgets

, which defines GUI widgets, layouts, and other high-level GUI components

Those three modules will be used in nearly any PyQt program we write. Later in the book, we will explore other modules for graphics, networking, web rendering, multimedia, and other advanced capabilities.

Introducing Qt Designer

Before we wrap up our introduction to Qt, let's look at a free tool offered by the Qt company that can help us create PyQt applications—Qt Designer.

Qt Designer is a graphical WYSIWYG GUI designer for Qt. Using Qt Designer, you can drag and drop GUI components into an application and configure them without having to write any code at all. While it is certainly an optional tool, you may find it useful for prototyping, or preferable to hand-coding a large and complex GUI. While most of the code in this book will be hand-coded, we will be covering the use of Qt Designer with PyQt in Chapter 2, Building Forms with Qt Widgets, and Chapter 3, Handling Events with Signals and Slots.

Using Qt Designer

Let's take a moment to get familiar with how to launch and use Qt Designer:

Launch

Qt Creator

Select

File 

New File or Project

Under

Files and Classes,

select

Qt

Choose

Qt Designer Form

Under

Choose a Template Form,

select

Widget,

then click

Next

Give your form a name and click

Next

Click

Finish

You should see something that looks like this: 

If you installed Qt Designer as a standalone application on Linux, launch it with the designer command or select it from your program's menu. You shouldn't need the previous steps.

Take a few minutes to test out Qt Designer:

Drag some widgets from the left pane onto your base widget

Resize the widgets if you wish, or select one and examine its properties in the lower-right pane

When you've made several changes, select

Tools 

Form Editor 

Preview

,

or hit

Alt

Shift

R

, to preview your GUI

In Chapter 2, Building Forms with Qt Widgets, we'll go into detail on how to use Qt Designer to build a GUI interface; for now, you can find out more information about Qt Designer from the manual at https://doc.qt.io/qt-5/qtdesigner-manual.html.

Summary

In this chapter, you learned about the Qt application framework and the PyQt Python bindings for Qt. We wrote a Hello World application and created a template for building larger Qt applications. Finally, we installed and took our first look at Qt Designer, the GUI editor.

In Chapter 2, Building Forms with Qt Widgets, we'll get familiar with some of the basic Qt widgets and learn how to resize and arrange them in a user interface. You'll then apply that knowledge by designing a calendar application in both code and Qt Designer.

Further reading

Check out these resources for more information on Qt, PyQt, and Qt Designer:

The

PyQt manual

at

http://pyqt.sourceforge.net/Docs/PyQt5/

is a handy resource for understanding PyQt's distinct aspects

The

Qt module list

at

https://doc.qt.io/qt-5/qtmodules.html

gives a good rundown of the available modules in Qt

The

QApplication

documentation at

https://doc.qt.io/qt-5/qapplication.html#QApplication

lists all the command-line switches parsed by the

QApplication

object

The

QWidget

documentation at

https://doc.qt.io/qt-5/qwidget.html

shows the properties and methods available in the

QWidget

object

The

Qt Designer manual

at

https://doc.qt.io/qt-5/qtdesigner-manual.html

will help you explore the full capabilities of Qt Designer

If you want to understand more about C++, check out these offerings from Packt 

https://www.packtpub.com/tech/C-plus-plus

Building Forms with QtWidgets

One of the first steps in application development is prototyping your app's GUI. With a wide range of ready-to-use widgets, PyQt makes this very easy. Best of all, we can move our prototype code directly into an actual application when we're done.

In this chapter, we're going to get familiar with basic form design over the following topics:

Creating basic QtWidgets widgets

Placing and arranging widgets

Validating widgets

Building a calendar application GUI

Technical requirements

To complete this chapter, you'll need everything from Chapter 1, Getting Started with PyQt, plus the example code from https://github.com/PacktPublishing/Mastering-GUI-Programming-with-Python/tree/master/Chapter02.

Check out the following video to see the code in action: http://bit.ly/2M2R26r

Creating basic QtWidgets widgets

The QtWidgets module contains dozens of widgets, some simple and standard, others complex and unique. In this section, we're going to go through eight of the most common widgets and their basic usage.

Before starting this section, make a copy of your application template from Chapter 1, Getting Started with PyQt, and save it to a file called widget_demo.py. As we go through the examples, you can add them into your MainWindow.__init__() method to see how the objects work.