The previous chapters have focused on learning how to manually code GUIs using PyQt. This was done intentionally so that you could have a better fundamental understanding of the code and processes used to create simple applications. Chapters 2 and 3 showed you how to create your own GUI from scratch. In Chapter 4, you learned about layouts and how to arrange widgets by coding them yourself. You saw how to create applications with menus and toolbars in Chapter 5 and how to style their look in Chapter 6.
While setting up and arranging GUIs yourself gives you more control over the design process, not everyone will need or want to take the time to do so. Fortunately, Qt provides a great application for setting up the layouts and designing main windows, widgets, or dialogs. Qt Designer is a graphical interface filled with Qt widgets and other tools used for building GUIs. Using the Qt Designer application’s drag and drop interface, you are able to create and customize your own dialogs, windows, and widgets.
The widgets and other applications you create using Qt Designer integrate with programmed code, using Qt’s signals and slots mechanism, so that you can easily assign behavior to widgets and graphical elements. This means that rather than focusing most of your time on layout and design, you can get into coding the functionality of an application much faster.
Find out about the Qt Designer user interface
Create an application in Qt Designer, including how to set layouts, edit object properties, connect signals and slots, and generate Python code
Learn about the QFrame class for containing other widgets
Be introduced to a couple new Qt classes including QPalette and QIntValidator
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-5/qtdesigner-manual.html.
Getting Started with Qt Designer
Once you have installed PyQt, the first thing you need to do is to launch the Qt Designer application. After opening Qt Designer, you will see a graphical user interface for creating your own GUIs like the one in Figure 7-1.
For more information about downloading and launching Qt Designer for Windows, MacOS, and Linux, refer to Appendix A.
If you are using a stand-alone version of Qt Designer, then you can change the configuration of Qt Designer under Settings. Locate the Preferences menu, and in the dialog box that appears, you can change the appearance of Qt Designer from a Multi Top-Level Windows user interface to one using Docked Windows. Otherwise, the multilevel layout is only available if you use Qt Creator, the integrated development environment (IDE) for working with Qt.
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 7-1.
Exploring Qt Designer’s User Interface
At the top of the main window in Figure 7-1, you will notice Qt Designer’s menubar and toolbar for managing and editing your GUI. On the left side of the main window is the Widget Box dock widget, shown in Figure 7-3, which provides an organized list of layouts and widgets that can be dragged and dropped onto the required locations of your GUI. Other features for tinkering with the form can be accessed by right-clicking and opening up various context menus.
Another very useful dock widget is the Property Editor displayed in Figure 7-4. The properties of windows, widgets, and layouts such as an object’s name, size constraints, status tips, and more can all be altered using the Property Editor. Each widget you add to a form will have its own set of properties as well as ones that the widget inherits from other classes. To select a specific widget, you can either click the object in the form or the widget’s name in the Object Inspector dock widget.
The Object Inspector allows you to view all of the objects that are currently being used as well as their hierarchical layout. In Figure 7-5, you can see how the MainWindow is listed first, followed by the centralwidget and all of its widgets. If your form also has a menu or toolbar, then they will also be listed in the Object Inspector along with their corresponding actions.
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.
Finally, there is the Resource Browser which allows you specify and manage resources you need to use in your application. These resources can include images and icons. The Resource Browser dock widget can be seen in Figure 7-8.
If you need to add resources, you first need to create a new resource file. To do so, click the pencil in the top-left corner of the Resource Browser dock widget. This will open an Edit Resources dialog similar to the one in Figure 7-9. Next, click 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.
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 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/Slots 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’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 to make your application easier to use.
Creating an Application in Qt Designer
- 1.
Select a form – In the New Form dialog (shown in Figure 7-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 the objects in the form and edit their features in the Property Editor dock widget.
- 4.
Connect signals and slots – Use the Signal/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 7.1 – Keypad GUI
Keypad GUI Solution
The keypad application is comprised of two Python files, keypad_gui.py and keypad_main.py. The keypad_gui.py contains all of the Python code generated from the UI file created using Qt Designer. In order to use that code, we then 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, twelve QPushButton widgets, and a single QLabel to display information about how to use the interface. The asterisk button allows users to clear the current input and the hash button is for confirming the user’s four-digit input.
This project introduces the QFrame container for organizing Qt widgets. The program also utilizes nested layouts to arrange the various widgets and containers.
The following Python code in Listing 7-1 is produced from the UI file using pyuic. It has not been altered. To help you understand the code, Listing 7-1 is broken into parts with annotations.
Code for keypad created from keypad.ui
Code for the keypad GUI created from keypad.ui
When you run the code, your GUI should look similar to Figure 7-11.
Explanation
In order to utilize the Ui_Keypad class that was created using Qt Designer, we create a new Python file, keypad_main.py. The KeypadGUI class created in keypad_main.py will inherit from the Ui_Keypad class.
We begin by importing the modules needed for this project, including the Ui_Keypad class and a new Qt class, QIntValidator. Qt provides a few classes that can be used to verify the types of input text. QIntValidator will be used to check if the values input into the QLineEdit widgets are integers.
In the initializeUI() method, local modifications are made to the QLineEdit widgets. Here the line edit widget’s focus policy is set to NoFocus so that users can only enter input in the correct order.
Then we connect the signals and slots for the button widgets. When each button is clicked, it sends a signal that is connected to the numberClicked() slot . Rather than creating a separate method for each button, the lambda function is used to reuse a method for signals. lambda calls the numberClicked() function and passes it a new parameter every time, in this case the specific text from each button.
When a user clicks a button, that button’s number needs to appear in the correct line edit widget from left to right. A widget receives focus if its text() value is empty. On MacOS, the repaint() method was used to update the text in the QLineEdit widgets. repaint() is used to force a widget to update itself.
Finally, if the user presses the # button, the method checkPasscode() checks if the user entered the passcode that matches self.passcode. If the input does not match, the line edit widgets are reset. This project could be designed so that the password is read from a file or from a database.
We have taken a look at the user interface class created from Qt Designer and at the file that inherits from it. The following section shows in detail how to create the GUI in Qt Designer.
Select a Form
Arrange Objects on the Form
From here you could immediately begin to adjust certain features of the form such as the window size or the background color. Instead, let’s begin by adding whatever widgets you may need for your project by dragging and dropping them into the main window from the Widget Box on the left of the window.
The QFrame Class
A frame object can have a number of different styles of frames, including boxes, panels, or lines. The style of the frame can be adjusted using the setFrameShadow(), setLineWidth(), and setMidLineWidth() methods.
Apply Layouts in Qt Designer
The next step is to add layouts to all of the containers and to the main window, as well. This is important to make sure that 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 – and Qt Designer will take care of placing them by using a widget’s size hint. For more information about the types of layouts in PyQt, refer to Chapter 4.
Edit 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 7-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 them in the form or in the Object Inspector. If a property is edited in the Property Editor, you can locate it by the following pattern:
Qt Class (Property column) ➤ Property name ➤ (submenu, if any) ➤ Value
- 1.
Change window title: QWidget ➤ windowTitle ➤ 7.1 ➤ Keypad GUI
- 2.
Double-click the QLabel. Change text to Enter a passcode.
- 3.Change QLabel properties:
- a.
QWidget ➤ font ➤ 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
- a.
- 4.Change top frame properties:
- a.
QWidget ➤ sizePolicy ➤ Vertical Stretch ➤ 1
- b.
QFrame ➤ frameShape ➤ NoFrame
- c.
QFrame ➤ frameShadow ➤ Plain
- a.
- 5.For each of the four QLineEdit widgets, modify their properties:
- a.
QWidget ➤ sizePolicy ➤ Vertical Policy ➤ Expanding
- b.
QWidget ➤ font ➤ font ➤ Point Size ➤ 30
- c.
QLineEdit ➤ alignment ➤ Horizontal ➤ AlignHCenter
- a.
- 6.Change bottom frame properties:
- a.
QWidget ➤ sizePolicy ➤ Vertical Stretch ➤ 2
- b.
QFrame ➤ frameShape ➤ Box
- c.
QFrame ➤ frameShadow ➤ Sunken
- d.
QFrame ➤ lineWidth ➤ 2
- a.
- 7.
Double-click each of the buttons and change their text to 0–9, ∗, and #.
- 8.Edit each of the buttons’ properties:
- a.
QWidget ➤ sizePolicy ➤ Vertical Policy ➤ Expanding
- b.
QWidget ➤ font ➤ font ➤ Point Size ➤ 36
- a.
- 9.Resize the main window:
- a.
QWidget ➤ geometry ➤ Width ➤ 302
- b.
QWidget ➤ geometry ➤ Height ➤ 406
- a.
- 10.
Click the form and change its background color: QWidget ➤ palette ➤ Change Palette ➤ Window ➤ dark gray
- 11.
In the Object Inspector, double-click each of the default object names and edit them. The object name is used to reference the objects in the code.
After you have followed along with each of the steps, the form should look similar to Figure 7-11.
Connect 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 the object that will emit a signal and drag it to the object that will receive the signal, which is the slot.
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 the ‘∗’ button is clicked, we want to clear all four line edit widgets. Click the button and drag the red arrow to the first line edit object. A dialog box will appear (displayed in Figure 7-16) that allows you to select the methods for both the signal and the slot. Select clicked() for the button and clear() for the line edit. Finish connecting the other three line edit widgets. Refer to Figure 7-17 as a guide for connecting the widgets.
When connecting signals and slots, make sure to check the “Show signals and slots inherited from QWidget” checkbox to access more methods.
Preview 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 hot keys Ctrl+R for Windows or Cmd+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.
Create and Edit Python Code
Qt Designer uses the Qt utility User Interface Compiler (uic) to generate code and create the user interface. However, since you are using PyQt5, you must use the uic Python module, pyuic5, to load .ui files and convert the XML file to Python code.
If you make changes to the GUI in Qt Designer after creating the Python file, you will need to call pyuic5 again on the UI file.
While it is possible to write new code in the newly generated Python file, the best thing to do would be to create a new file that imports the new user interface class. If you need to make changes to the GUI in Qt Designer and resave the file, it will erase any new code that you have written.
Extra Tips for Using Qt Designer
Creating GUIs with menus
Displaying images in Qt Designer
Setting Up Main Windows and Menus
Open Qt Designer and select the Main Window template from the Form Menu in Figure 7-2. This creates a main window with a menubar and status bar by default. You can see a main window form displayed in Figure 7-1.
Adding Menus and Submenus in Qt Designer
Adding Toolbars in Qt Designer
Toolbars can be added to the main window by right-clicking the form to open a context menu. Click 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 hot key, and made checkable all in the Action Editor dock widget (shown in Figure 7-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.
Display Images in Qt Designer
This last 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 widget 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, shown below in Figure 7-21. Scroll down until you find the pixmap property . Click 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 look for the icon property, not pixmap.
Summary
Qt Designer is definitely a useful tool for creating GUI applications. It provides a drag and drop interface that makes it easier to lay out 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 that can be included in Qt Designer or generating dialog boxes.
The following chapters will begin to look at more specific classes that can be used to further augment a user interface. Chapter 8 takes a look at the QClipboard class and creating widgets with drag and drop functionality.