Previous Next

Create GUI Applications with Python Qt6 (Version 5.0, 2022-05-25, PySide6) (Martin Fitzpatrick) (z-library.sk, 1lib.sk, z-lib.sk)

Author: Martin Fitzpatrick

Python

No Description

📄 File Format: PDF
💾 File Size: 13.9 MB
11
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
Create GUI Applications with Python & Qt6 The hands-on guide to making apps with Python Martin Fitzpatrick Version 5.0, 2022-05-25
📄 Page 3
Table of Contents Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  1 1. A very brief history of the GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  3 2. A bit about Qt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  5 Basic PySide6 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  7 3. My first Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  8 4. Signals & Slots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  19 5. Widgets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  33 6. Layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  66 7. Actions, Toolbars & Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  94 8. Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  118 9. Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  168 10. Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  180 Qt Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  190 11. Installing Qt Designer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  191 12. Getting started with Qt Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  196 13. The Qt Resource system. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  215 Theming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  226 14. Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  227 15. Palettes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  229 16. Icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  238 17. Qt Style Sheets (QSS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  246 Model View Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  301 18. The Model View Architecture — Model View Controller . . . . . . . . . . . . . . .  302 19. A simple Model View — a Todo List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  304 20. Tabular data in ModelViews, with numpy & pandas . . . . . . . . . . . . . . . . . . .  322 21. Querying SQL databases with Qt models . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  347 Custom Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  379 22. Bitmap Graphics in Qt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  380 23. Creating Custom Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  412 24. Using Custom Widgets in Qt Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  447 Concurrent Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  456 25. Introduction to Threads & Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  457
📄 Page 4
26. Using the thread pool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  464 27. QRunnable examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  476 28. Long-running threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  542 29. Running external commands & processes . . . . . . . . . . . . . . . . . . . . . . . . . . . .  560 Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  570 30. Plotting with PyQtGraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  571 31. Plotting with Matplotlib. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  593 Further PySide6 Features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  611 32. Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  612 33. Extending Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  619 34. Working with Relative Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  630 35. System tray & macOS menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  636 36. Enums & the Qt Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  647 37. Working with command-line arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  658 38. Pythonic PySide6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  663 Packaging & Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  666 39. Packaging with PyInstaller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  667 40. Creating a Windows installer with InstallForge . . . . . . . . . . . . . . . . . . . . . . .  696 41. Creating a macOS Disk Image Installer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  708 42. Creating a Linux Package with . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  712 Example applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  723 43. Mozzarella Ashbadger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  724 44. Moonsweeper. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  745 Appendix A: Installing PySide6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  771 Appendix B: Translating C++ Examples to Python. . . . . . . . . . . . . . . . . . . . . . . . . . .  774 Appendix C: PyQt6 and PySide6 — What’s the difference? . . . . . . . . . . . . . . . . . . .  787 Appendix D: What next?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  800 45. Thank you . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  801 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  802
📄 Page 5
Introduction If you want to create GUI applications with Python it can be tricky to know where to start. There are a lot of new concepts you need to understand to get anything to work. But, like any coding problem, the first step is learning to approach the problem in the right way. In this book I take from the basic principles of GUI development to creating your own, fully functional, desktop apps with PySide6. The first edition of this book was released in 2016. Since then it has been updated 14 times, adding and expanding chapters in response to reader feedback. There are more PySide resources available now than when I started, but there is still a shortage of in-depth, practical guides to building complete apps. This book fills that gap! The book is formatted as a series of chapters exploring different aspects of PySide6 in turn. They are arranged to put the simpler chapters toward the beginning, but if you have specific requirements for your project, don’t be afraid to jump around. Each chapter will guide you through learning the fundamental concepts before taking you through a series of coding examples to gradually explore and learn how to apply the ideas yourself. You can download source code and resources for all examples in this book from http://www.pythonguis.com/d/pyside6-source.zip It is not possible to give you a complete overview of the entire Qt ecosystem in a book of this size, so there are links to external resources — both on the pythonguis.com website and elsewhere. If you find yourself thinking "I wonder if I can do that?" the best thing you can do is put this book down, then go and find out! Just keep regular backups of your code along the way so you always have something to come back to if you royally mess it up. 1
📄 Page 6
 Throughout this book there are boxes like this, giving info, tips and warnings. All of them can be safely skipped over if you are in a hurry, but reading them will give you a deeper and more rounded knowledge of the Qt framework. 2
📄 Page 7
1. A very brief history of the GUI The Graphical User Interface has a long and venerable history dating back as far as the 1960s. Stanford’s NLS (oN-Line System) introduced the mouse and windows concepts, first demonstrated publicly in 1968. This was followed by the Xerox PARC Smalltalk system GUI 1973, which is the foundation of most modern general purpose GUIs. These early systems already had many of the features we take for granted in modern desktop GUIs, including windows, menus, radio buttons, check boxes and icons. This combination of features gave us the early acronym used for these types of interfaces: WIMP (windows, icons, menus, pointing device — a mouse). In 1979 the first commercial system featuring a GUI was released — the PERQ workstation. This spurred a number of other GUI efforts including, notably, the Apple Lisa (1983), which added the concept of the menu bar and window controls, as well as other systems from Atari (GEM) and Amiga. On UNIX, the X Window System emerged in 1984 while the first version of Windows for PC was released in 1985. Figure 1. The desktop on Microsoft Windows 3.1 (1992) and Apple System 7 (1991) Early GUIs were not the instant hit you might think, due to the lack of compatible software at launch and expensive hardware requirements — particularly for home users. However, slowly, but steadily, the GUI paradigm become the 3
📄 Page 8
preferred way to interact with computers and the WIMP metaphor became firmly established as the standard. That’s not to say there haven’t been attempts to replace the WIMP metaphor on the desktop. Microsoft Bob (1995), for example, was Microsoft’s much maligned attempt to replace the desktop with a house. Figure 2. Microsoft Bob — Discarding the desktop metaphor for a cartoon house. There has been no shortage of user interfaces hailed as revolutionary in their time, from the launch of Windows 95 (1995) through to Mac OS X (2001), GNOME Shell (2011) and Windows 10 (2015). Each of these overhauled the UI of their respective systems, often with much fanfare, but fundamentally nothing really changed. These user interfaces are still very much WIMP systems and function in much the same way as GUIs have since the 1980s. When the revolution came, it was mobile — the mouse has been replaced by touch, and windows by full-screen apps. But even in a world where we all walk around with smartphones in our pocket, a huge amount of daily work is still done on desktop computers. WIMP has survived 40 years of innovation and looks to survive many more. 4
📄 Page 9
2. A bit about Qt Qt is a free and open-source widget toolkit for creating cross-platform GUI applications, allowing applications to target multiple platforms from Windows, macOS, Linux and Android with a single codebase. But Qt is much more than a widget toolkit and features built in support for multimedia, databases, vector graphics and MVC interfaces, it is more accurate to think of it as an application development framework. Qt was started by Eirik Chambe-Eng and Haavard Nord in 1991, founding the first Qt company Trolltech in 1994. Qt is currently developed by The Qt Company and continues to be regularly updated, adding features and extending mobile and cross-platform support. Qt and PySide6 PySide6, also known as Qt for Python is a Python binding of the Qt toolkit, currently developed by The Qt Company. When you write applications using PySide6 what you are really doing is writing applications in Qt. The PySide6 library is actually a wrapper around the C++ Qt library, which makes it possible to use it in Python. Because this is a Python interface to a C++ library, the naming conventions used within PySide6 do not adhere to PEP8 standards. For example, functions and variables are named using mixedCase rather than snake_case. Whether you adhere to this standard in your own applications is entirely up to you, however I find it helpful to continue to follow Python standards for my own code, to help clarify where the PySide6 code ends and your own begins. Lastly, while there is PySide6 specific documentation available, you will often find yourself reading the Qt documentation itself as it is more complete. If you need advice on converting Qt C++ code to Python, take a look at Translating C++ Examples to Python. 5
📄 Page 10
with DR.MARTIN FITZPATRICK ACADEMY Updates & Additional Resources This book is regularly updated. If you bought this book from me directly you’ll receive automatic digital updates as they are released. If you bought the book elsewhere, send your receipt to register@pythonguis.com to get the latest digital edition & register for future updates. You may also be interested in joining my Python GUI Academy where I have video tutorials covering the topics in this book & beyond! Join me at academy.pythonguis.com
📄 Page 11
Basic PySide6 Features It’s time to take your first steps in creating GUI applications with PySide6! In this chapter you will be introduced to the basics of PySide6 that are the foundations of any application you create. We will develop a simple windowed application on your desktop. We’ll add widgets, arrange them using layouts and connect these widgets to functions, allowing you to trigger application behavior from your GUI. Use the provided code as your guide, but always feel free to experiment. That’s the best way to learn how things work.  Before you get started, you need a working installation of PySide6. If you don’t have one yet, check out Installing PySide6.  Don’t forget to download the source code that accompanies this book from http://www.pythonguis.com/d/pyside6-source.zip 7
📄 Page 12
3. My first Application Let’s create our first application! To start create a new Python file — you can call it whatever you like (e.g. myapp.py) and save it somewhere accessible. We’ll write our simple app in this file.  We’ll be editing within this file as we go along, and you may want to come back to earlier versions of your code, so remember to keep regular backups. Creating your App The source code for your very first application is shown below. Type it in verbatim, and be careful not to make mistakes. If you do mess up, Python will let you know what’s wrong. If you don’t feel like typing it all in, the file is included in the source code with this book. 8
📄 Page 13
Listing 1. basic/creating_a_window_1.py from PySide6.QtWidgets import QApplication, QWidget # Only needed for access to command line arguments import sys # You need one (and only one) QApplication instance per application. # Pass in sys.argv to allow command line arguments for your app. # If you know you won't use command line arguments QApplication([]) works too. app = QApplication(sys.argv) # Create a Qt widget, which will be our window. window = QWidget() window.show() # IMPORTANT!!!!! Windows are hidden by default. # Start the event loop. app.exec() # Your application won't reach here until you exit and the event # loop has stopped. First, launch your application. You can run it from the command line like any other Python script, for example —  python MyApp.py Or, for Python 3 —  python3 MyApp.py From now on, you’ll see the following box as a hint to run your application and test it out, along with an indication of what you’ll see. 9
📄 Page 14
 Run it! You will now see your window. Qt automatically creates a window with the normal window decorations and you can drag it around and resize it like any window. What you’ll see will depend on what platform you’re running this example on. The image below shows the window as displayed on Windows, macOS and Linux (Ubuntu). Figure 3. Our window, as seen on Windows, macOS and Linux. Stepping through the code Let’s step through the code line by line, so we understand exactly what is happening. First, we import the PySide6 classes that we need for the application. Here we’re importing QApplication, the application handler and QWidget, a basic empty GUI widget, both from the QtWidgets module. from PySide6.QtWidgets import QApplication, QWidget The main modules for Qt are QtWidgets, QtGui and QtCore.  You could use from <module> import * but this kind of global import is generally frowned upon in Python, so we’ll avoid it here. 10
📄 Page 15
Next we create an instance of QApplication, passing in sys.arg, which is Python list containing the command line arguments passed to the application. app = QApplication(sys.argv) If you know you won’t be using command line arguments to control Qt you can pass in an empty list instead, e.g. app = QApplication([]) Next we create an instance of a QWidget using the variable name window. window = QWidget() window.show() In Qt all top level widgets are windows — that is, they don’t have a parent and are not nested within another widget or layout. This means you can technically create a window using any widget you like.  I can’t see my window! Widgets without a parent are invisible by default. So, after creating the window object, we must always call .show() to make it visible. You can remove the .show() and run the app, but you’ll have no way to quit it!  What is a window? • Holds the user-interface of your application • Every application needs at least one (…but can have more) • Application will (by default) exit when last window is closed Finally, we call app.exec() to start up the event loop. 11
📄 Page 16
What’s the event loop? Before getting the window on the screen, there are a few key concepts to introduce about how applications are organised in the Qt world. If you’re already familiar with event loops you can safely skip to the next section. The core of every Qt Application is the QApplication class. Every application needs one — and only one — QApplication object to function. This object holds the event loop of your application — the core loop which governs all user interaction with the GUI. Figure 4. The event loop in Qt. Each interaction with your application — whether a press of a key, click of a mouse, or mouse movement — generates an event which is placed on the event queue. In the event loop, the queue is checked on each iteration and if a waiting event is found, the event and control is passed to the specific event handler for the event. The event handler deals with the event, then passes control back to the event loop to wait for more events. There is only one running event loop per application. 12
📄 Page 17
 The QApplication class • QApplication holds the Qt event loop • One QApplication instance required • Your application sits waiting in the event loop until an action is taken • There is only one event loop at any time QMainWindow As we discovered in the last part, in Qt any widgets can be windows. For example, if you replace QtWidget with QPushButton. In the example below, you would get a window with a single push-able button in it. Listing 2. basic/creating_a_window_2.py import sys from PySide6.QtWidgets import QApplication, QPushButton app = QApplication(sys.argv) window = QPushButton("Push Me") window.show() app.exec() This is neat, but not really very useful — it’s rare that you need a UI that consists of only a single control! But, as we’ll discover later, the ability to nest widgets within other widgets using layouts means you can construct complex UIs inside an empty QWidget. But, Qt already has a solution for you — the QMainWindow. This is a pre-made widget which provides a lot of standard window features you’ll make use of in your apps, including toolbars, menus, a statusbar, dockable widgets and more. 13
📄 Page 18
We’ll look at these advanced features later, but for now, we’ll add a simple empty QMainWindow to our application. Listing 3. basic/creating_a_window_3.py from PySide6.QtWidgets import QApplication, QMainWindow import sys app = QApplication(sys.argv) window = QMainWindow() window.show() # IMPORTANT!!!!! Windows are hidden by default. # Start the event loop. app.exec()  Run it! You will now see your main window. It looks exactly the same as before! So our QMainWindow isn’t very interesting at the moment. We can fix that by adding some content. If you want to create a custom window, the best approach is to subclass QMainWindow and then include the setup for the window in the __init__ block. This allows the window behavior to be self contained. We can add our own subclass of QMainWindow — call it MainWindow to keep things simple. 14
📄 Page 19
Listing 4. basic/creating_a_window_4.py import sys from PySide6.QtCore import QSize, Qt from PySide6.QtWidgets import (   QApplication,   QMainWindow,   QPushButton, ) ① # Subclass QMainWindow to customize your application's main window class MainWindow(QMainWindow):   def __init__(self):   super().__init__() ②   self.setWindowTitle("My App")   button = QPushButton("Press Me!")   # Set the central widget of the Window.   self.setCentralWidget(button) ③ app = QApplication(sys.argv) window = MainWindow() window.show() app.exec() ① Common Qt widgets are always imported from the QtWidgets namespace. ② We must always call the __init__ method of the super() class. ③ Use .setCentralWidget to place a widget in the QMainWindow.  When you subclass a Qt class you must always call the super __init__ function to allow Qt to set up the object. 15
📄 Page 20
In our __init__ block we first use .setWindowTitle() to change the title of our main window. Then we add our first widget — a QPushButton — to the middle of the window. This is one of the basic widgets available in Qt. When creating the button you can pass in the text that you want the button to display. Finally, we call .setCentralWidget() on the window. This is a QMainWindow specific function that allows you to set the widget that goes in the middle of the window.  Run it! You will now see your window again, but this time with the QPushButton widget in the middle. Pressing the button will do nothing, we’ll sort that next. Figure 5. Our QMainWindow with a single QPushButton on Windows, macOS and Linux.  Hungry for widgets? We’ll cover more widgets in detail shortly but if you’re impatient and would like to jump ahead you can take a look at the QWidget documentation. Try adding the different widgets to your window! Sizing windows and widgets The window is currently freely resizable — if you grab any corner with your mouse you can drag and resize it to any size you want. While it’s good to let your users resize your applications, sometimes you may want to place restrictions on 16
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now

Recommended for You

Loading recommended books...
Failed to load, please try again later
Back to List