While building GUIs programmatically gives you more control over the design process, some development tasks may require a quicker approach. Fortunately, Qt provides a great interface for arranging widgets and designing main windows, widgets, or dialogs. The graphical development tool, Qt Designer , is filled with widgets and other tools for building GUIs. With the application’s drag-and-drop interface, you are able to create and customize your own Qt or PyQt applications.
The widgets and other applications you create using Qt Designer can interact with other Qt programs using signals and slots, making it easier to assign behaviors to widgets. This means that more resources can go into coding the functionality and less into layout and design.
Install the Qt Designer application
Take a look at the different components that comprise the Qt Designer interface
Follow along and build an application in Qt Designer, along the way learning how to apply layouts, edit object properties, connect signals and slots, and generate Python code
Learn about new PyQt classes such as QFrame class for grouping widgets
For references or more help beyond the scope of this chapter, check out the Qt Documentation for Qt Designer at https://doc.qt.io/qt-6/qtdesigner-manual.html.
This chapter serves as an introduction to Qt Designer, providing you with the fundamentals you need to get started using the application.
Getting Started with Qt Designer
In this section, we’ll first consider two methods for installing Qt Designer on your computer. After that, we’ll discuss the layout of the Qt Designer GUI.
Installing Qt Designer
As of writing, there are two approaches to installing the latest version of Qt Designer, and they can vary depending upon how much memory you are willing to use.
Your first option is to download the latest version of Qt Creator for Qt 6 from www.qt.io/download. Qt Designer comes bundled with Qt Creator, which is Qt’s official C++ IDE. Be aware that this method works for macOS, Windows, and Linux, but also means that you will be installing the entire Qt Creator IDE as well.
On the Qt downloads web page, you’ll need to locate the option for downloading Qt for open source creators. From there, scroll to the bottom of the page and find the button that says Download the Qt Online Installer. Once the download completes, you’ll need to open up the Qt installer software. You’ll need to create a Qt Account and then follow along with the prompts to install Qt Creator. One thing to note, if you choose to perform a custom installation, you’ll be able to manually select the software you need and save some memory. Once the installation is complete, do a search on your computer to locate Qt Designer.
Use pip instead of pip3 on Windows.
You can change the appearance of the Qt Designer window. In the menu bar, locate the Preferences… menu option, and in the dialog box that appears, look for User Interface Mode. You can select two appearances: Multi Top-Level Windows or Docked Windows. The multilevel layout is great for arranging all of the widgets freely on larger screens.
Before you create your first application, let’s get to know the different menus, tools, and modes that are displayed in the main window in Figure 8-1.
Exploring Qt Designer’s User Interface
The main layout for your GUI is not displayed in the Object Inspector. A broken layout icon (a red circle with a slash) is displayed on the central widget or on containers if no layout has been assigned to them.
Next, click on the Create New Resource button, navigate to the correct directory, and enter a name for the resource file. The file will be saved with a .qrc file extension, which stands for Qt Resource Collection and contains a list of all the resources used in your program. From here, create a prefix for managing the types of resources and begin adding files such as images and icons. When you are finished, click the OK button, and the files will be added to the Resource Browser.
Support for resources and .qrc files in PyQt6 is different than in PyQt5. To access the resources, you may have to consider using other PyQt classes, such as QFile or QDir, or use the file path to the resource.
Qt Designer’s Editing Modes
- 1.
Edit Widgets – Widgets can be dragged and dropped to a form, layouts can be applied, and objects can be edited both on the form and in the Property Editor. This is the default mode.
- 2.
Edit Signals/Slots – Connect signals and slots for widgets and layouts. To create connections, click on an object and drag the cursor toward an object that will receive the signal. Items that can be connected will be highlighted as the mouse cursor moves over them. To create the connection, release the mouse button once a line with an arrow connects the two objects. Then configure the signals and slots. Use in conjunction with the Signal/Slot Editor dock widget to edit connections.
- 3.
Edit Buddies – Connect QLabel widgets with shortcuts to input widgets such as QLineEdit or QTextEdit. The input widget becomes the QLabel object’s “buddy.” When the user enters the label’s shortcut key, the focus moves to the input widget.
- 4.
Edit Tab Order – Set the order in which widgets receive focus when the tab key is pressed. This allows the user to navigate through the different widgets, improving your application’s usability.
Creating an Application in Qt Designer
- 1.
Select a form – In the New Form dialog (shown in Figure 8-2), choose from one of the available templates, Main Window, Widget, or a type of Dialog. You can also add and preview widgets to include in your GUI.
- 2.
Arrange objects on the form – Use Qt Designer’s drag-and-drop mechanics to place widgets on the form. Then assign layouts to containers and the main window.
- 3.
Edit the properties of objects – Click on the objects in the form and edit their features in the Property Editor dock widget.
- 4.
Connect signals and slots – Use the Signals/Slots Editing mode to link signals to slots.
- 5.
Preview your GUI – Examine the form before saving it as a UI file with the .ui extension.
- 6.
Create and edit Python code – Utilize the pyuic compiler to convert the UI file to readable and editable Python code.
The following project will cover these steps in addition to many of the basic concepts for creating GUIs using Qt Designer.
Project 8.1 – Keypad GUI
Keypads are relatively simple interfaces, with sets of buttons for digits, symbols, or letters used as input devices for passcodes or telephone numbers. They can be found on a number of devices such as calculators, cell phones, and locks.
Explanation for the Keypad GUI
The keypad application is composed of two Python files: keypad_gui.py and keypad_main.py. The keypad_gui.py contains the Python class generated from the UI file built from Qt Designer. In order to use that code, we need to create a customized class in a separate file, keypad_main.py, to import and set up the GUI.
The keypad GUI consists of four QLineEdit widgets to input only numeric values, 12 QPushButton widgets, and a single QLabel to display information about how to use the interface. The asterisk button allows users to clear their current input, and the hash button is for confirming the user’s four-digit input.
We’ll begin by creating the window in Qt Designer before discussing the code.
Selecting a Form
Begin by opening up Qt Designer. Choose the Widget template from the New Form dialog box. We will use the Default screen size. Select Create. This opens up a blank QWidget form with a grid of dots inside of the Qt Designer interface similar to Figure 8-1 (although that screenshot displays a QMainWindow form).
Arranging Objects on the Form
You could begin by adjusting certain features of the form such as the window size or the background color. Instead, let’s first add whatever widgets we need for the project by dragging and dropping them into the main window from the Widget Box dialog on the left of the window.
Before moving on, let’s take a moment to learn more about the QFrame container as it is a very useful element in GUI development.
The QFrame Class
Using the method setSizePolicy(), we can define how a frame should resize. A frame object can have a number of different styles of frames, including Box, Panel, StyledPanel, or NoFrame. The style of the frame can be adjusted using the setFrameShadow(), setLineWidth(), and setMidLineWidth() methods. Different types of shadow include Plain, Raised, and Sunken.
For practice, try creating a simple window from the previous code.
Applying Layouts in Qt Designer
The next step is to add layouts to all of the containers and to the main window. This is an important step that ensures items are placed and resized correctly. Layouts can be added either from the toolbar or from context menus. It is possible to add more widgets to existing layouts once they have been set.
Since Qt Designer uses a drag-and-drop interface, you only need to place the objects on the form close to where you want them to be and then select one of the four layouts – QGridLayout, QHBoxLayout, QVBoxLayout, or QFormLayout – from the Widget Box dialog, and Qt Designer will take care of arranging them. For more information about the types of layouts in PyQt, refer to Chapter 4.
Editing the Properties of Objects
Once you have the layouts prepared, you should begin editing the features of the objects. This step could also be accomplished earlier when you place objects on the form.
The Property Editor is shown in Figure 8-4. It is organized into two columns: Property and Value. The properties are organized by Qt Classes.
To access and make changes to specific containers, widgets, layouts, or even the main window, you can click on them in the form or in the Object Inspector. If a property is edited in the Property Editor, you can locate it with the following pattern:
Qt Class (Property column) ➤ Property name ➤ (submenu, if any) ➤ Value column ➤ parameter
- 1.
Change window title: QWidget ➤ windowTitle ➤ 8.1 – Keypad GUI
- 2.
Double-click on the QLabel. Change text to enter a passcode.
- 3.Change QLabel properties:
- a.
QWidget ➤ font ➤ Point Size ➤ 20
- b.
To edit palette colors, you will need to locate the palette property that opens a dialog box. Here, you can change the colors for different parts of an object. To change the color of the text in the label object: QWidget ➤ palette ➤ Change Palette ➤ Window Text ➤ white
- c.
QLabel ➤ alignment ➤ Horizontal ➤ AlignHCenter
- 4.Change top frame properties:
- a.
QWidget ➤ sizePolicy ➤ Vertical Stretch ➤ 1
- b.
QFrame ➤ frameShape ➤ NoFrame
- c.
QFrame ➤ frameShadow ➤ Plain
- 5.For each of the four QLineEdit widgets, modify their properties:
- a.
QWidget ➤ sizePolicy ➤ Vertical Policy ➤ Expanding
- b.
QWidget ➤ font ➤ Point Size ➤ 30
- c.
QLineEdit ➤ alignment ➤ Horizontal ➤ AlignHCenter
- 6.Change bottom frame properties:
- a.
QWidget ➤ sizePolicy ➤ Vertical Stretch ➤ 2
- b.
QFrame ➤ frameShape ➤ Box
- c.
QFrame ➤ frameShadow ➤ Sunken
- d.
QFrame ➤ lineWidth ➤ 2
- 7.
Double-click on each of the buttons and change their text to 0–9, *, and #. (Refer to Figure 8-11.)
- 8.Edit each of the button’s properties:
- a.
QWidget ➤ sizePolicy ➤ Vertical Policy ➤ Expanding
- b.
QWidget ➤ font ➤ Point Size ➤ 36
- 9.Resize the main window:
- a.
QWidget ➤ geometry ➤ Width ➤ 302
- b.
QWidget ➤ geometry ➤ Height ➤ 406
- 10.
Click on the form and change its background color: QWidget ➤ palette ➤ Change Palette ➤ Window ➤ dark gray
- 11.
In the Object Inspector, double-click on each of the default object names for the frames, line edits, and buttons, and edit them. Doing this will be helpful later on so that we can distinguish the buttons when looking at the code. The object name is used to reference the objects.
After you have followed along with each of the steps, the form should look similar to Figure 8-11.
Previewing Your GUI
It is often useful to view and interact with the form before exporting it to code. Not only can this be useful for checking the visual appearance of your GUI, but previewing also helps to make sure the signals and slots, resizing the window, and other functions are working properly.
To preview a form, open the Form menu and select Preview or use the hotkeys Ctrl+R for Windows or Command+R for macOS. If you are satisfied with your form, save it as a UI file with the .ui extension. Qt Designer UI files are written in XML format and contain the widget tree representation for creating a GUI.
Connecting Signals and Slots in Qt Designer
Switch to the Edit Signals/Slots mode by selecting it from the toolbar. Qt Designer has a simple interface for connecting signals and slots. Click on the object that will emit a signal and drag it to the object that will receive the signal. For the keypad GUI, we are only making one set of connections. The remaining signals and slots will be handled by manually coding them.
When connecting signals and slots, make sure to check the “Show signals and slots inherited from QWidget” checkbox to access more methods.
Creating Python Code from Qt Designer
Qt Designer uses the Qt utility User Interface Compiler (uic) to generate code and create the user interface. However, since you are using PyQt6, you must use the uic module, pyuic6, to load .ui files and convert the XML code to Python code. The pyuic6 utility is a command line interface for interacting with uic.
To output a Python file, you need to include the -o flag and the Python file to be written to, filename.py. This command will generate a single Python class.
If you make changes to the GUI in Qt Designer after creating the Python script, you will need to call pyuic6 again to update the application.
Change python3 to python on Windows.
Generating Code Using pyuic6
Python class created from keypad.ui
PyQt6 modules are first imported. The Ui_Keypad class inherits object, denoting that this class is the root for all other classes.
From there, the member function setupUi() of the class Ui_Keypad is used to build a widget tree on the Keypad widget. A widget tree is used to represent the organization of widgets in a UI. So the setupUi() method is passed a widget that will display the interface (typically QWidget, QDialog, or QMainWindow) and compose the UI based upon the widgets and connections we used to create it along with the parameters it inherits.
Every widget in Qt has a palette that contains information about how they will be drawn in the window. The QPalette class contains the color groups for each widget during one of three possible states – Active, Inactive, or Disabled.
Setting up the palette for the keypad GUI
You can see that even though we only changed the palette color, that change is handled for all three states automatically. The QBrush class is used to apply the colors and patterns to widgets. The setPalette() method applies palette to the Keypad class.
Creating the main window’s layout manager
Creating the header label
The changes to label instance’s font and alignment are also reflected in the code.
Creating the frame for the QLineEdit widgets in the keypad GUI
Code for the QLineEdit widgets in the keypad GUI
There is a lot of repetition in this large block of code. That is because the four line edits all have the same changes made. By looking at one instance, you can understand the other three.
Each of the four line edit widgets has size policies that allow them to stretch if the window resizes in both the vertical and horizontal directions by using QSizePolicy.Policy.Expanding. Changes made to the font size and the alignment also show up. The QLineEdit widgets are then arranged in the horizontalLayout of the frame container. The frame object is finally added to the verticalLayout of the main window.
Creating the frame for the QPushButton widgets in the keypad GUI
The bottom frame is guaranteed to take up more vertical space since its vertical stretch factor is set to 2. The frame has a Box shape, Sunken shadow, and lineWidth of 2. The layout inside frame_2 holds the 12 buttons and uses a grid layout.
Creating the QPushButton widgets that are arranged in the bottom frame
The 12 QPushButton widgets are created. The buttons are able to expand vertically using the Expanding flag, and their font size is set to 36. Every button is then added to the grid layout of frame_2, which is then added to the vertical layout of the main window.
Connecting the signals and slots for the keypad GUI
Code for the retranslateUi() method
QCoreApplication.translate returns the translated text of the second argument passed to the method.
Creating a New Script to Build a GUI
The following section creates the class that inherits Ui_Keypad and sets up the GUI application. In order to utilize the Ui_Keypad class that was created using Qt Designer, we’ll create a new Python file, keypad_main.py. The KeypadGUI class created in keypad_main.py will inherit from the Ui_Keypad class.
Setting up the main window for the keypad GUI
Code for the initializeUI() method in the keypad GUI
Setting up the signals for the push buttons in the keypad GUI
Creating the numberClicked() slot
The repaint() method is used to ensure that text is updated in the QLineEdit widgets.
Creating the checkPasscode() slot
A QMessageBox appears to inform the user about the outcome of their password. When you run this script, your GUI should look similar to Figure 8-11.
We have only covered some of the features of Qt Designer while building the keypad GUI. In the following section, we’ll look at a few other important topics.
Extra Tips for Using Qt Designer
- 1.
Creating GUIs with menus
- 2.
Displaying images in Qt Designer
- 3.
Using style sheets
Setting Up Main Windows and Menus
Open Qt Designer and select the Main Window template from the Form Menu in Figure 8-2. This creates a main window with a menu bar and status bar by default. You can see a main window form displayed in Figure 8-1.
Adding Menus and Submenus in Qt Designer
Adding Toolbars in Qt Designer
Toolbars can be added to the main window by right-clicking on the form to open a context menu. Click on the Add Tool Bar option.
Adding Actions in Qt Designer
When items are first created in the menu and the toolbar, they are actually actions. Actions can be created, removed, given an icon, designated a shortcut hotkey, and made checkable all in the Action Editor dock widget (shown in Figure 8-7). Actions can also be shared between the menu and the toolbar.
To share an action between the menu and the toolbar so that both objects contain the same item, drag the action from the Action Editor that already exists in the menu onto the toolbar.
Displaying Images in Qt Designer
This section will take a quick look at how you can include images and icons in your application. Whether you are looking to add an image to a QLabel or trying to add icons to your toolbar, the process for adding an image is similar.
For example, if you have a QLabel widget on your form, you can access its properties in the Property Editor. Scroll down until you find the pixmap property. Click on its Value, and from here, you will be able to search for an image file. If you want to add an icon, then you will use the icon property, not pixmap.
Adding Style Sheets in Qt Designer
Here, you can use the drop-down arrows to select different properties and change colors, add resources, or change fonts.
That wraps up this chapter’s examination of Qt Designer.
Summary
Qt Designer is definitely a useful tool for creating GUI applications. It provides a drag-and-drop interface that makes it easier to organize widgets; modify the parameters of objects; create menus, toolbars, and dock widgets; add actions to menus; generate code that can be used in Python; and more. Qt Designer can make the design process much quicker and easier.
While this chapter covered a few of the basics for using Qt Designer, there are still other uses, such as creating your own custom widgets or building dialog boxes.
The following chapters will begin to look at more specific PyQt classes and topics that can be used to further improve user interfaces. In the next chapter, you will discover how to use the QClipboard class for copying and pasting data between different applications.