To create a GUI for your windows and dialogs in PyQt, you can take two main paths: you tin use Qt Designer, or you lot tin hand lawmaking the GUI in plain Python code. The first path can dramatically meliorate your productivity, whereas the 2d path puts you in full control of your application'southward code.

GUI applications often consist of a chief window and several dialogs. If you're looking to create these graphical components in an efficient and user-friendly mode, then Qt Designer is the tool for you. In this tutorial, you'll learn how to use Qt Designer to create your GUIs productively.

In this tutorial, you lot'll learn:

  • What Qt Designer is and how to install it on your system
  • When to utilize Qt Designer vs hand coding for edifice your GUIs
  • How to build and lay out the GUI of an application'southward principal window using Qt Designer
  • How to create and lay out the GUI of your dialogs with Qt Designer
  • How to use Qt Designer'south .ui files in your GUI applications

For a meliorate understanding of the topics in this tutorial, you can check out the following resources:

  • Python and PyQt: Building a GUI Desktop Reckoner
  • Python and PyQt: Creating Menus, Toolbars, and Condition Bars
  • PyQt Layouts: Create Professional-Looking GUI Applications

You'll put all this cognition together past using the GUIs that you'll build with Qt Designer in a sample text editor application. You can get the code and all the required resource to build this application by clicking the link below:

Getting Started With Qt Designer

Qt Designer is a Qt tool that provides you with a what-you lot-encounter-is-what-you-become (WYSIWYG) user interface to create GUIs for your PyQt applications productively and efficiently. With this tool, y'all create GUIs past dragging and dropping QWidget objects on an empty form. After that, you tin can arrange them into a coherent GUI using different layout managers.

Qt Designer too allows you to preview your GUIs using unlike styles and resolutions, connect signals and slots, create menus and toolbars, and more than.

Qt Designer is platform and programming linguistic communication independent. It doesn't produce code in any particular programming linguistic communication, simply it creates .ui files. These files are XML files with detailed descriptions of how to generate Qt-based GUIs.

Y'all tin translate the content of .ui files into Python code with pyuic5, which is a command-line tool that comes with PyQt. Then you can apply this Python code in your GUI applications. You can as well read .ui files directly and load their content to generate the associated GUI.

Installing and Running Qt Designer

At that place are several means to get and install Qt Designer depending on your current platform. If you use Windows or Linux, then you tin can run the following commands from your terminal or command line:

                                                  $                  python3 -grand venv ./venv                  $                                    source                  venv/bin/actuate                  (venv)                  $                  pip install pyqt5 pyqt5-tools                              

Hither, y'all create a Python virtual environment, activate it, and install pyqt5 and pyqt5-tools. pyqt5 installs PyQt and a copy of the required Qt libraries, while pyqt5-tools installs a set of Qt tools that includes Qt Designer.

The installation will place the Qt Designer executable in a unlike directory co-ordinate to your platform:

  • Linux: ...lib/python3.x/site-packages/qt5_applications/Qt/bin/designer
  • Windows: ...Lib\site-packages\pyqt5_tools\designer.exe

On Linux systems, such equally Debian and Ubuntu, you tin can too install Qt Designer past using the system package director with the post-obit command:

                                                  $                  sudo apt install qttools5-dev-tools                              

This command downloads and installs Qt Designer and other Qt tools on your organisation. In other words, you'll have a organization-wide installation and you'll be able to run Qt Designer past clicking its icon in a file manager or system menu.

On macOS, if you lot've installed Qt from Homebrew using the brew install qt command, so you should have Qt Designer already installed on your system.

Finally, y'all tin can download the Qt installer for your current platform from the official download site then follow the on-screen instructions. In this case, to complete the installation procedure, you need to register a Qt account.

If yous've already installed Qt Designer using one of the options discussed then far, then get ahead and launch the application. You should get the post-obit two windows on your screen:

Qt Designer GUI

The window in the foreground is Qt Designer'due south New Form dialog. The window in the groundwork is Qt Designer's master window. In the next ii sections, you'll learn the basics of how to use these components of the Qt Designer interface.

Using Qt Designer's New Form Dialog

When you run Qt Designer, you lot're presented with the application'south primary window and the New Form dialog. In this dialog, y'all tin select from five bachelor GUI templates. These templates include options to create dialogs, main windows, and custom widgets:

Template Form Type Widgets Base Class
Dialog with Buttons Bottom Dialog OK and Cancel buttons laid out horizontally on the lesser-right corner QDialog
Dialog with Buttons Right Dialog OK and Cancel buttons laid out vertically on the peak-right corner QDialog
Dialog without Buttons Dialog No QDialog
Main Window Primary Window A menu bar at the top and a status bar at the bottom QMainWindow
Widget Widget No QWidget

By default, when you run Qt Designer, the New Form dialog appears in the foreground. If information technology doesn't, then you can click New on Qt Designer'south toolbar. You lot can also click File → New in the master card or press Ctrl + N on your keyboard.

In the New Course dialog, yous can select the form template that y'all want to start with and and then click Create to generate a new course:

To create a new and empty form using a Qt Designer template, you just need to select the desired template from the New Form dialog and and then click Create or press Alt + R on your keyboard.

Note that the outset 2 dialog templates accept their own default buttons. These are standard buttons included in a QDialogButtonBox. This grade automatically handles the position or order of buttons across different platforms.

For example, if yous employ a Abolish button and an OK button, then the standard on Linux and macOS is to brandish those buttons in this same gild. Only on Windows, the guild of buttons will be swapped, with OK appearing beginning, followed past Abolish. QDialogButtonBox handles this consequence for you automatically.

Working With Qt Designer's Main Window

Qt Designer's main window provides a menu bar with options for saving and managing forms, editing forms and changing the edit mode, laying out and previewing forms, and also for tuning the application's settings and accessing its help documentation:

Qt Designer Main Menu

The main window also provides a toolbar that displays commonly used options. You'll utilize about of these options when you're editing and laying out your forms. These options are as well available in the principal menu, especially in the File, Edit, and Form menus:

Qt Designer Toolbar

Qt Designer's primary window too includes a few dock windows that provide a rich set of features and tools:

  • Widget Box
  • Object Inspector
  • Property Editor
  • Resource Browser
  • Activeness Editor
  • Bespeak/Slot Editor

The Widget Box provides a selection of layout managers, spacers, standard widgets, and other objects that you can use to create a GUI for your dialogs and windows:

The Widget Box provides a filter option at the pinnacle of the window. You lot can type the name of a given object or widget and get quick access to it. The objects are grouped into categories that reflect their specific use. You lot can prove or hide all the available objects in a category by clicking the handle adjacent to the category label.

When you're creating your forms, you can take objects from the Widget Box with your mouse arrow and and so drag and drop them onto the course to build its GUI.

The Widget Box also provides a Scratchpad section at the bottom of the window. In this section, you can group frequently used objects in a separate category. You tin make full the Scratchpad category with any widget currently placed on a class by dragging and dropping them back onto the Widget Box. You lot tin can remove widgets from the Scratchpad category by correct-clicking them and selecting Remove in the context menu.

The Object Inspector provides a tree view of all the objects on the current form. The Object Inspector as well has a filter box at the top to allow yous to find objects in the tree. You can use the Object Inspector to set the proper name and other backdrop of the form and its widgets. You tin can likewise right-click whatever widget to access a context menu with additional options:

With the Object Inspector, you can manage the widgets on your form. You can rename them, update some of their properties, remove them from the form, and so on. The tree view in the Object Inspector reflects the parent-kid relationship of the widgets and objects on the current class.

The Property Editor is another dock window that appears in Qt Designer's main window. This window holds a 2-column table with the active object's properties and their values. You can use the Property Editor to edit the value of an object's properties, every bit the proper noun implies:

The Holding Editor provides a user-friendly way to access and edit the values of the active object's properties, such as its name, size, font, icon, so on. The properties listed on the editor will alter depending on which object you select on your class.

The properties are listed from top to bottom according to course hierarchy. For example, if you lot select a QPushButton on the course, and so the Property Editor shows the properties of QWidget, followed by the properties of QAbstractButton, and finally the properties of QPushButton itself. Note that the rows on the editor testify different colors to visually differentiate the underlying grade.

Finally, you have iii dock windows that commonly appear equally tabs in the bottom-right corner:

  1. Resource Browser provides a quick way of adding resource, such as icons, translation files, images, and other binary files to your applications.
  2. Action Editor provides a mode to create actions and add them to your forms.
  3. Signal/Slot Editor provides a manner to connect signals and slots in your forms.

Here are some of the options that these tools provide:

Qt Designer Action Signal Resource

That's information technology! These three dock windows round out the prepare of tools and options that Qt Designer provides for you to create and customize the GUIs for your dialogs and windows.

Using Qt Designer vs Mitt Coding Your GUIs

With PyQt, y'all have at least two options for creating the GUI of a window or dialog: You tin can use Qt Designer, or y'all tin can hand code the GUI in plain Python code. Both options take their pros and cons. Sometimes information technology's hard to decide when to use i or the other.

Qt Designer provides a user-friendly graphical interface that allows you to quickly create GUIs. This tin can boost your productivity as a developer and shorten your development cycles.

Mitt coding your GUIs, on the other hand, tin can give yous much more than control over them. With this arroyo, adding new components and features doesn't require whatever extra tools beyond your code editor or IDE, which can be quite convenient in some development environments.

Whether you apply Qt Designer or mitt code your GUIs is a personal decision. Hither are some general considerations on both approaches:

Feature Qt Designer Hand Coding
Developer'south productivity High High if you're familiar with PyQt, but low otherwise
Separation of GUI logic from business logic Loftier Low
Control over GUI components Depression High
Capability for adding and removing widgets dynamically Low Loftier
Flexibility for exploration, learning, prototyping, and sketching High Low
Flexibility for using custom widgets Low Loftier
Amount of boilerplate code High Low

Beyond these concerns, if you're just starting with PyQt, and so Qt Designer can help you discover available widgets, layout managers, base classes, backdrop and their typical values, so on.

One concluding departure between using Qt Designer and mitt coding a GUI is that y'all need to run an extra footstep when using Qt Designer: translating .ui files into Python code.

Edifice Main Windows With Qt Designer and Python

With PyQt, you can build master window–mode and dialog-style applications. Chief window–style applications oftentimes consist of a chief window with a menu bar, 1 or more toolbars, a key widget, and a status bar. They can too include several dialogs, but those are independent of the main window.

Qt Designer enables you to chop-chop build the GUI of your main windows using the predefined Main Window template. One time y'all've created a course based on that template, yous'll have tools to perform the following actions:

  • Creating a main menu
  • Adding and populating toolbars
  • Laying out widgets

Qt Designer'due south Main Window template also provides a default central widget and a status bar at the bottom of the window:

Qt Designer saves its forms in .ui files. These are XML files that contain all the information you'll need to afterwards recreate the GUI in your applications.

To salvage your forms, get to File → Salve, enter main_window.ui in the Save Form As dialog, select a directory to save the file in, and click Save. You tin can besides get access to the Save Course Every bit dialog by pressing Ctrl + S on your keyboard.

Don't close your Qt Designer session—stay there to continue adding menus and toolbars to the master window you merely created.

Creating the Main Menu

Qt Designer'southward Principal Window template provides an empty menu bar at the top of the form. You can add together menus to that bill of fare bar using the Menu Editor. Menus are pull-down lists of options that provide quick admission to the awarding'south options. Become dorsum to Qt Designer and your newly created main window. At the top of the form, you lot'll see a carte du jour bar with the placeholder text Blazon Hither.

If you double-click or press Enter on this placeholder text, so you can type the proper name of your first menu. To confirm the menu proper noun, just press Enter .

Say you want to create your own text editor. Typically, this kind of awarding has a File menu with at least some of the following options:

  • New for creating a new document
  • Open for opening an existing document
  • Open Recent for opening recently viewed documents
  • Relieve for saving a document
  • Get out for exiting the application

Hither's how yous can use Qt Designer to create this menu:

Qt Designer Main Menu Editor

Qt Designer'southward Menu Editor allows yous to add menus to the menu bar in a user-friendly mode. When you enter the name of a menu or bill of fare choice, you can use an ampersand symbol (&) earlier a given letter to provide a keyboard accelerator.

For example, if you add an ampersand before the F in the File menu, and so yous tin access this menu by pressing Alt + F . Likewise, if you add together an ampersand before the N in New, then once y'all've launched the File carte du jour, you tin access the New choice past pressing Due north .

With the Menu Editor, yous can also add separators to your menus. This is a proficient way to visually separate menu options and group them logically. To add a separator, double-click the Add Separator option at the terminate of the active menu in the Menu Editor. You lot tin remove an existing separator past correct-clicking it then selecting Remove Separator in the context menu. This menu also allows you to add new separators.

If you demand to move a separator to some other place in a given menu, then you lot can drag the separator to the desired position and driblet it in that location. A reddish line will betoken the position where the separator will exist placed.

Y'all can likewise add a submenu to a given menu option. To do this, click the icon on the right side of the carte du jour selection to which y'all desire to attach the submenu, just similar you lot did with the Open up Recent option in the above example.

To run a preview of your form, go to Course → Preview, or hit the fundamental combination Ctrl + R on your keyboard.

When you create a menu like the File menu in your sample text editor, a new QMenu object is automatically added to your menu bar. When you add a menu option to a given menu, y'all create an action. Qt Designer provides an Activity Editor for creating, customizing, and managing actions. The tool provides a few handy options that you can use to fine-tune your actions:

With the Action Editor, you can fine-melody, update, or ready the following options:

  • The text of the action, which volition be shown on bill of fare options and toolbar buttons
  • The object proper noun, which you'll use in your code to reference the action object
  • The icons that will be shown on your menu options and toolbar buttons
  • The checkable property of the action
  • The keyboard shortcuts, which will provide the user with a quick mode to access the action

The concluding ellipsis (...) in the text of your menu options is a widely used convention for naming options that don't perform an firsthand action just launch a pop-up dialog for performing further actions.

In the case of the icons, you demand to pack those icons with your application every bit independent files, or you can create a resources file, also known as a .qrc file. For this example, you can download the required icons and other resources by clicking the link below:

Once you've downloaded the icons, create a resource directory abreast your main_window.ui file and re-create the icons there. Then get back to the Action Editor and add icons to your actions like this:

Note that your carte du jour options now display an icon on the left margin. This provides extra visual information to your users and helps them find the desired option. At present go ahead and add an Edit carte du jour with the following options:

  • Re-create for copying some text
  • Paste for pasting some text
  • Cut for cutting some text
  • Discover and Replace for finding and replacing text

Adjacent, add a Help menu with an Virtually option for launching a dialog with full general information near your text editor. Finally, go to the Property Editor and set the championship of your window to Sample Editor. After these additions, your principal window should await something like this:

Sample Text Editor Main Menu

With these additions, your sample text editor'south main menu is starting to wait similar the carte du jour of a real text editor!

Creating a Toolbar

You can add as many toolbars every bit you need to your master window'southward GUI using Qt Designer. To do that, right-click on the grade and select Add Tool Bar from the context card. This adds an empty toolbar at the tiptop of the window. Alternatively, y'all can predefine the toolbar area where you want to place a given toolbar by selecting Add Tool Bar to Other Surface area:

Qt Designer Create Toolbars

One time you have your toolbars in place, you can populate them with buttons. To do this, you employ actions rather than specific toolbar buttons from the Widget Box. To add deportment to your toolbars, yous tin use the Activity Editor:

Actions can exist shared between card options and toolbar buttons, so in this instance, you reuse the actions that you lot created when you lot populated your menus in the preceding section. To populate the toolbar, click on an activeness on the Action Editor, then drag and driblet it onto the toolbar. Notation that by right-clicking on the toolbar, yous tin can add separators to visually dissever the tool buttons.

Laying Out a Single Central Widget

Qt Designer uses QMainWindow for building its Main Window template. This class provides a default layout that allows you to create a menu bar, i or more toolbars, 1 or more than dock widgets, a status bar, and a primal widget. By default, Qt Designer uses a QWidget object as the central widget on the Primary Window template.

Using a blank-bones QWidget object as the central widget on a main window's GUI is a skillful pick because, on height of that widget, you can place either a single widget or multiple widgets in a coherent layout.

For example, in your sample text editor, you lot might want to use a single widget that provides your users with a work expanse to blazon, re-create, paste, and edit their text. For this purpose, you can utilise a QTextEdit object and then add a vertical (or horizontal) layout as the central widget's layout:

In this example, you first drag a QTextEdit onto the form. And so you click on the form to select your central widget. Finally, y'all apply a vertical layout to your primal widget past clicking Lay Out Vertically on Qt Designer's toolbar.

Since the spacing effectually the QTextEdit doesn't look right, you use the Object Inspector to change the margins of the layout from 9 pixels to 1 pixel.

With Qt Designer, you tin can use different layout managers to arrange your widgets quickly. Arguably, the most attainable fashion of laying out your GUIs with Qt Designer is using the layout-related section on the principal toolbar:

Qt Designer Layout Toolbar

From left to correct, you'll notice the following options to create dissimilar types of layouts:

Pick Widget Arrangement Layout Class Keyboard Shortcut
Lay Out Horizontally Horizontally in 1 row and several columns QHBoxLayout Ctrl + 1
Lay Out Vertically Vertically in 1 column and several rows QVBoxLayout Ctrl + 2
Lay Out Horizontally in Splitter Horizontally in a resizable splitter QSplitter Ctrl + 3
Lay Out Vertically in Splitter Vertically in a resizable splitter QSplitter Ctrl + 4
Lay Out in a Grid Tabularly in a grid with several rows and columns QGridLayout Ctrl + 5
Lay Out in a Class Layout Tabularly in a two-column table QFormLayout Ctrl + 6

The last two options in the toolbar are related to layouts but don't create them:

  1. Break Layout allows y'all to pause an existing layout. Once widgets are bundled in a layout, y'all tin't move or resize them individually because their geometry is controlled by the layout. To modify individual widgets, you might need to interruption the layout and redo it later. To admission this option, you lot can press Ctrl + 0 on your keyboard.

  2. Adjust Size adjusts the size of the layout to conform independent widgets and to ensure that each has enough infinite to be visible. To access this selection, y'all can press Ctrl + J on your keyboard.

Yous can also admission all these layout-related options through Qt Designer's main menu bar, under the Grade menu:

Qt Designer Form Menu

In the Form menu, you accept admission to all the layout-related options, with a complete reference of the keyboard shortcuts to access them. You lot can also access these options through the course'south context menu, under the Lay Out choice.

Laying Out a Chemical compound Central Widget

When you're creating your chief windows, you lot might face situations in which you need to employ multiple widgets in a given layout every bit your cardinal widget. Since Qt Designer's Chief Window template ships with a QWidget object as its central widget, you lot can take advantage of this to create your own custom arrangement of widgets and then gear up it as the top-level layout of that central widget.

With Qt Designer, you tin lay out your widgets using layout managers, as you already saw in the above section. If you need a compound layout of widgets for your main window's GUI, and then you can build information technology by running the following steps:

  1. Drag and driblet the widgets onto your course and endeavour to place them about their desired position.
  2. Select the widgets that should be managed together by a given layout.
  3. Employ the appropriate layout using Qt Designer's toolbar or master menu, or with the form's context menu.

Although you can elevate layouts onto a form and so drag widgets onto the layouts, the all-time practice is to drag all the widgets and spacers first and then repeatedly select related widgets and spacers to utilise layouts to them.

For instance, suppose you lot're edifice a computer application. Y'all need a QLineEdit object on the acme of your grade to display the operations and their results. Under the line edit, you need a few QPushButton objects for the numbers and operations. That gives you a window like this:

Calculator No Layout

This looks something like a calculator, just the GUI is messy and chaotic. To arrange this into a more than polished computer GUI, y'all can use a filigree layout for the buttons and a vertical box layout as the calculator's meridian-level layout:

Your figurer still needs some extra polishing, but information technology looks a lot amend now. To get a more than finished version, you can use the Property Editor to tweak the values of some properties on your buttons, such as their maximum and minimum size. You can as well set a stock-still size for your figurer's main window, so on. Go ahead and give it a try!

Having a Status Bar

Qt Designer'south Main Window template provides a status bar past default. A condition bar is a horizontal panel that's usually placed at the bottom of the chief window in a GUI application. Its primary purpose is to brandish data nigh the current status of the application.

You can divide a status bar into several sections and show different data on each section. The information on the status bar can be temporary or permanent, and most of the time information technology comes as text messages. The purpose of the information displayed on the status bar is to continue your users updated well-nigh what the awarding is currently doing and what its full general status is at a given time.

Yous can also use the status bar to brandish help tips, which are brusk assist letters that describe what a given button or menu selection does. This kind of bulletin appears on the status bar when the user hovers the mouse arrow over a toolbar push or menu option.

Creating a Dialog With Qt Designer and Python

Dialogs are pocket-sized-sized windows that yous commonly use to provide auxiliary functionalities, such equally a Preferences dialog, or to communicate with your users by showing fault messages or full general information virtually a given operation. You can likewise use dialogs to inquire the user for some required information or to ostend an operation that's virtually to accept place.

PyQt offers a rich set of born dialog that you tin can use in your applications straight. You just need to import them from PyQt5.QtWidgets. Here'south a summary:

All these built-in dialogs are set for y'all to use in your code directly. Most of them provide class methods to build specific types of dialogs depending on your needs. Along with these dialogs, PyQt provides the QDialog course. Y'all can apply this course to create your own dialogs in code, but you can also utilize Qt Designer to create your dialogs rapidly.

In the next few sections, yous'll learn how to create, lay out, and customize your dialogs using Qt Designer and its dialog templates.

Creating a Dialog GUI

To create a custom dialog with Qt Designer, select the advisable template for the dialog from the New Grade dialog. Drag and drop the required widgets onto the class, lay out them correctly, and save the form in a .ui file for later utilize in your application.

Go back to your sample text editor and suppose you want to add a Discover and Replace dialog like this:

Find Replace Dialog

To create this dialog, start with the Dialog without Buttons template and add the required widgets to the class:

Here, yous showtime create an empty dialog using the Dialog without Buttons template and prepare the window title to Find and Supercede in the Object Inspector. Then you drag and driblet two QLabel objects onto the course using the Widget Box. These labels inquire the users for the words they demand to find and replace. Those words will be entered in the respective QLineEdit objects near the labels.

Side by side, you drag and drop three QPushButton objects onto the form. These buttons will allow your users to find and replace words in their current document. Finally, you add together two QCheckBox objects to provide Match Case and Lucifer Whole Discussion options.

One time you have all the widgets on the course, brand sure to place them in a position that's similar to what yous want to achieve in your terminal dialog. Now it's time to lay out the widgets.

Laying Out the Dialog GUI

Equally you lot saw before, to arrange the widgets in a course, yous can use several layout managers. To lay out your Observe and Replace dialog, use a grid layout for the labels, line edits, and checkboxes. For the buttons, employ a vertical layout. Finally, use a horizontal layout equally your dialog's top-level layout manager:

Here, you select the labels, line edits, and checkboxes with your mouse pointer and apply a filigree layout to them. Later that, you lot add a vertical spacer between the Supervene upon and Cancel buttons to keep them visually separated.

The final stride is to set the dialog's top-level layout. In this case, you use a horizontal layout manager. That's it! Yous've congenital the GUI of your Find and Replace dialog with Qt Designer. Save it with the filename find_replace.ui.

There are a bunch of other properties and features that you can tweak in your dialogs using Qt Designer. For example, you lot can gear up the tab order of your input widget to ameliorate the experience of users navigating your dialogs with their keyboard. You can too provide keyboard accelerators, connect signals and slots, and then on.

Connecting Signals and Slots

Then far, you've used Qt Designer in the Edit Widgets manner, which is its default way. In this mode, you tin can add widgets to your forms, edit widget'south backdrop, lay out the widgets on the form, and so on. However, Qt Designer has up to four different modes to allow you to work on unlike features of your forms:

Fashion Purpose Menu Option Keyboard Shortcut
Edit Widgets Editing widgets Edit → Edit Widgets F3
Edit Signals/Slots Connecting built-in signals and slots Edit → Edit Signals/Slots F4
Edit Buddies Setting up keyboard accelerators Edit → Edit Buddies No
Edit Tab Order Setting up the tab guild of widgets Edit → Edit Tab Order No

Y'all tin also admission these modes by clicking their corresponding buttons in the style-related section of Qt Designer's toolbar, which looks like this:

Qt Designer Mode Toolbar

To be able to edit the born signals and slots of your widgets and forms, you first need to switch to the Edit Signals/Slots mode.

User actions on widgets and forms, such every bit a click or a keypress, are known as events in PyQt. When an effect occurs, the widget at mitt emits a bespeak. This machinery allows yous to run actions in response to events. These actions are known as slots, which are methods or functions.

To execute a slot in response to an outcome, you need to select i of the signals emitted past the widget in response to an result and connect it to the desired slot.

Most widgets, including dialogs and windows, implement built-in signals that are emitted when a given outcome occurs on the widget. Widgets also provide born slots that allow you to perform certain standardized deportment.

To found a signal-and-slot connection between two widgets using Qt Designer, you demand to select the signal-provider widget with your mouse and and then drag and drop it over the slot-provider widget. This launches Qt Designer's Configure Connection dialog. At present go back to the Find and Replace dialog and switch to Qt Designer's Edit Signals/Slots way. Then elevate and drop the Abolish button onto the form:

Qt Designer Configure Connection Dialog

The Configure Connexion dialog has 2 panels. On the left panel, you can select a indicate from the bespeak-provider widget, and on the right panel, yous can select a slot from the slot-provider widget. To create the connection, press OK:

Qt Designer Create Connection

The connectedness appears as an arrow from the signal-provider widget to the slot-provider widget, indicating that the connection is established. You'll too run into the name of the betoken and the slot that you just connected.

In this case, you lot continued the clicked() point of the Cancel button with the turn down() slot of the dialog. At present when y'all click Cancel, your action will be ignored, and the dialog volition close.

To modify a connection, double-click the arrow or one of the labels. This displays the Configure Connexion dialog, in which you tin can change the signal or the slot involved in the connection according to your needs.

To delete a connexion, select the arrow that represents the connection or one of the labels that identify the indicate and slot, then press Del .

Setting the Tab Guild of Widgets

To improve the usability of your dialogs, you tin set a coherent tab order for your input widgets. The tab order is the order in which the widgets on your grade come up into focus when you press Tab or Shift + Tab on your keyboard.

If yous're using Qt Designer to create your forms, so the default tab order of your widgets is based on the order in which you identify each widget on the form. Sometimes this guild isn't correct, and when yous hit Tab or Shift + Tab , the focus jumps to an unexpected widget. Take a wait at the tab society behavior in your Observe and Replace dialog:

Find Replace Dialog Tab Order

The focus starts on the Find line edit, then information technology goes through the Supervene upon line edit, and so through the checkboxes, and finally through the buttons. What if you desire the focus to jump from the Find line edit to the Supersede line edit and then to the Find button? In this instance, you can modify the tab club of the input widgets on the dialog. Switch to Edit Tab Order fashion in Qt Designer. You lot'll see something like this:

Qt Designer Tab Order

In Edit Tab Gild mode, each input widget in the form shows a number that identifies its position in the tab-order chain. Y'all can change that gild past clicking on the numbers in the desired order:

Qt Designer Change Tab Order

Y'all modify the tab order of the input widgets by clicking the numbers in the desired society. Note that when yous select a number, it changes to cherry-red, indicating that this is the currently edited position in the tab-club chain. Numbers y'all oasis't gear up are shown in blue, and the numbers you take ready are shown in green. If yous make a fault, and so yous tin can restart the ordering by choosing Restart from the grade's context menu.

Providing Keyboard Accelerators

A keyboard accelerator is a central combination that you lot tin press on your keyboard to quickly motility the focus onto a given widget on a dialog or window. Normally, keyboard accelerators consist of the Alt key and a letter that identifies the widget or option that you want to access. This can assist y'all improve the usability of your applications.

To ascertain a keyboard accelerator on a widget that includes a label, such as a push or a checkbox, y'all just need to place an ampersand symbol (&) before the letter in the characterization text that you want to use in the accelerator. For case, place an ampersand before the C on the Abolish push of your Find and Replace dialog, run a preview, and press Alt + C like in the following example:

Qt Designer Set Accelerator

By placing an ampersand earlier the letter C in the text of the Cancel push button, y'all create a keyboard accelerator. If y'all press Alt + C on your keyboard, and so the Cancel button is selected and the dialog closes.

To define a keyboard accelerator on a widget that doesn't include a label, such every bit a line edit, you need to make that widget a buddy of a characterization object. There are four steps that you lot demand to accept if y'all desire to create a buddy connection:

  1. Select a letter in the text of the label to identify the buddy connection and provide the keyboard accelerator.
  2. Identify an ampersand (&) earlier the selected alphabetic character in the text of the label.
  3. Switch to Edit Buddies mode in Qt Designer.
  4. Drag and drop the label onto the buddy widget.

Here'southward how you tin create a buddy human relationship betwixt the Find label and its related line edit:

Qt Designer Set Buddies

To create a buddy relationship between a label and a widget, select the label with your mouse and drag it onto the input widget that you want to ready as its buddy. The label and the input widget will get buddies. From this indicate on, you can press Alt plus the selected letter in the characterization text to move the focus to the related widget.

Information technology's important to annotation that you lot shouldn't have two widgets with the same keyboard accelerator in a given form. This means that you demand to select a unique alphabetic character for each keyboard accelerator.

Become ahead and apply Qt Designer to set keyboard accelerators for the widgets on your Find and Supercede dialog. The final event should wait like the dialog y'all saw at the beginning of the section Creating a Dialog GUI.

Integrating Windows and Dialogs in an Awarding

Up to this point, you've learned how to create a GUI for your main windows and dialogs with Qt Designer. In this department, you'll acquire how to integrate those GUIs into your Python code and build a real application. There are 2 main approaches to do that in PyQt:

  1. Translating the content of your .ui files into Python lawmaking using pyuic5
  2. Loading the content of the .ui files dynamically using uic.loadUi()

The first approach uses pyuic5, which is a tool included in the PyQt installation that allows yous to interpret the content of a .ui file into Python code. This approach is widely used because of its efficiency. However, it has one drawback: every time you modify the GUI with Qt Designer, you need to generate the code again.

The second approach takes advantage of uic.loadUi() to dynamically load the content of a .ui file into your application. This arroyo is suitable when y'all're working with small-scale GUIs that don't involve substantial loading time.

Setting Up Windows and Dialogs for Employ

Now it's time to set up your windows and dialogs for use in a real application (in this case, a sample text editor). If you've been following this tutorial, and so you should have at least two .ui files:

  1. main_window.ui with the GUI of a sample text editor application
  2. find_replace.ui with the GUI of a Discover and Replace dialog

Become ahead and create a new directory called sample_editor/. Within this directory, create another directory chosen ui/ and copy your .ui files into it. Likewise, re-create the resource/ directory that contains the icons for your bill of fare options and toolbar buttons to the sample_editor/ui/ directory. So far, the structure of your application should wait like this:

                                sample_editor/ │ └── ui/     ├── resources/     │   ├── edit-copy.png     │   ├── edit-cut.png     │   ├── edit-paste.png     │   ├── file-exit.png     │   ├── file-new.png     │   ├── file-open.png     │   ├── file-save.png     │   └── aid-content.png     │     ├── find_replace.ui     └── main_window.ui                              

Since the main-window GUI is relatively complex, yous can use pyuic5 to interpret the content of main_window.ui into Python code.

You can download all the required code and resources to build your sample text editor by clicking the link beneath:

Now open a terminal and navigate to the sample_editor/ directory. Once you're in that location, run the following command:

                                                  $                  pyuic5 -o main_window_ui.py ui/main_window.ui                              

This command generates a Python module called main_window_ui.py from the ui/main_window.ui file and places information technology in your sample_editor/ directory. This module contains the Python code for your master window's GUI. Here's a small-scale sample of the code:

                                                  # -*- coding: utf-8 -*-                  # Course implementation generated from reading ui file 'ui/main_window.ui'                  #                  # Created past: PyQt5 UI code generator 5.fifteen.ane                  #                  # WARNING: Whatsoever manual changes made to this file will exist lost when pyuic5 is                  # run again.  Do not edit this file unless you know what you are doing.                  from                  PyQt5                  import                  QtCore                  ,                  QtGui                  ,                  QtWidgets                  form                  Ui_MainWindow                  (                  object                  ):                  def                  setupUi                  (                  self                  ,                  MainWindow                  ):                  MainWindow                  .                  setObjectName                  (                  "MainWindow"                  )                  MainWindow                  .                  resize                  (                  413                  ,                  299                  )                  self                  .                  centralwidget                  =                  QtWidgets                  .                  QWidget                  (                  MainWindow                  )                  # Snip...                  def                  retranslateUi                  (                  self                  ,                  MainWindow                  ):                  _translate                  =                  QtCore                  .                  QCoreApplication                  .                  translate                  MainWindow                  .                  setWindowTitle                  (                  _translate                  (                  "MainWindow"                  ,                  "Sample Editor"                  ))                  self                  .                  menu_File                  .                  setTitle                  (                  _translate                  (                  "MainWindow"                  ,                  "&File"                  ))                  # Snip...                              

Ui_MainWindow has all the code for generating the GUI of the sample editor's main window. Note that .setupUi() contains the lawmaking to create all the required widgets and lay them out on the GUI. .retranslateUi() contains code for internationalization and localization, but this topic is across the telescopic of this tutorial.

Now your working directory should expect similar this:

                                sample_editor/ │ ├── ui/ │   ├── resources/ │   │   ├── edit-copy.png │   │   ├── edit-cut.png │   │   ├── edit-paste.png │   │   ├── file-leave.png │   │   ├── file-new.png │   │   ├── file-open.png │   │   ├── file-save.png │   │   └── help-content.png │   │ │   ├── find_replace.ui │   └── main_window.ui │ └── main_window_ui.py                              

Since your Detect and Replace dialog is quite small, you can load its GUI directly from your .ui file using uic.loadUi(). This function takes a string with the path to a .ui file equally an statement and returns a QWidget subclass that implements the GUI.

This way of loading .ui files dynamically is rarely used in do. You can utilise it with pocket-size dialogs that don't require too much try to load. With this arroyo, y'all don't need to generate the Python lawmaking for the dialog's GUI every time you modify the .ui file with Qt Designer, which tin be a productivity and maintainability win in some cases.

At present that y'all've chosen a strategy for building each of your GUIs, it's fourth dimension to put everything together in a real application.

Putting Everything Together in an Awarding

With all the pieces in place for your sample text editor, you can create the application and write the required lawmaking to use the main window and the Detect and Supplant dialog. Burn up your favorite lawmaking editor or IDE in your sample_editor/ directory and create a new file chosen app.py. Add the following lawmaking to information technology:

                                                                      1                  import                  sys                                      2                                      3                  from                  PyQt5.QtWidgets                  import                  (                                      4                  QApplication                  ,                  QDialog                  ,                  QMainWindow                  ,                  QMessageBox                                      v                  )                                      six                  from                  PyQt5.uic                  import                  loadUi                                      7                                      8                  from                  main_window_ui                  import                  Ui_MainWindow                                      9                  ten                  course                  Window                  (                  QMainWindow                  ,                  Ui_MainWindow                  ):                  xi                  def                  __init__                  (                  self                  ,                  parent                  =                  None                  ):                  12                  super                  ()                  .                  __init__                  (                  parent                  )                  xiii                  self                  .                  setupUi                  (                  self                  )                  xiv                  cocky                  .                  connectSignalsSlots                  ()                  15                  16                  def                  connectSignalsSlots                  (                  self                  ):                  17                  self                  .                  action_Exit                  .                  triggered                  .                  connect                  (                  cocky                  .                  close                  )                  18                  self                  .                  action_Find_Replace                  .                  triggered                  .                  connect                  (                  cocky                  .                  findAndReplace                  )                  xix                  self                  .                  action_About                  .                  triggered                  .                  connect                  (                  self                  .                  almost                  )                  20                  21                  def                  findAndReplace                  (                  self                  ):                  22                  dialog                  =                  FindReplaceDialog                  (                  self                  )                  23                  dialog                  .                  exec                  ()                  24                  25                  def                  about                  (                  self                  ):                  26                  QMessageBox                  .                  nigh                  (                  27                  self                  ,                  28                  "Most Sample Editor"                  ,                  29                  "<p>A sample text editor app congenital with:</p>"                  30                  "<p>- PyQt</p>"                  31                  "<p>- Qt Designer</p>"                  32                  "<p>- Python</p>"                  ,                  33                  )                  34                  35                  form                  FindReplaceDialog                  (                  QDialog                  ):                  36                  def                  __init__                  (                  self                  ,                  parent                  =                  None                  ):                  37                  super                  ()                  .                  __init__                  (                  parent                  )                  38                  loadUi                  (                  "ui/find_replace.ui"                  ,                  self                  )                  39                  40                  if                  __name__                  ==                  "__main__"                  :                  41                  app                  =                  QApplication                  (                  sys                  .                  argv                  )                  42                  win                  =                  Window                  ()                  43                  win                  .                  show                  ()                  44                  sys                  .                  exit                  (                  app                  .                  exec                  ())                              

Hither's what this code does:

  • Line 3 imports the required PyQt classes to build the application and the GUI.
  • Line 6 imports loadUi() from the uic module. This function provides a fashion of loading the content of a .ui file dynamically.
  • Line 8 imports Ui_MainWindow, which contains the GUI for your principal window.
  • Line 10 defines Window, which volition provide your application's chief window. In this case, the class uses multiple inheritance. It inherits the master window functionality from QMainWindow and the GUI functionality from Ui_MainWindow.
  • Line xiii calls .setupUi(), which creates the whole GUI for your chief window.
  • Line 16 defines .connectSignalsSlots(), which connects the required signals and slots.
  • Line 21 defines .findAndReplace(). This method creates an instance of your Find and Supercede dialog and execute it.
  • Line 25 defines .near(), which creates and launches a modest dialog to provide data about the application. In this example, you apply a built-in dialog based on QMessageBox.
  • Line 35 defines FindReplaceDialog, which provides the Detect and Supplant dialog.
  • Line 38 calls loadUi() to load the dialog'southward GUI from the files ui/find_replace.ui.

Finally, on lines 41 to 44, yous create the application, create and show the main window, and run the application'due south main loop past calling .exec() on the application object.

It's of import to notation that Qt Designer can name your deportment a bit differently from what yous saw in the above code. For instance, y'all might find the proper noun .actionE_xit instead of .action_Exit to refer to the Exit action. And so, for this example to work properly, you need to make sure you're using the right names.

If you want to employ your own names instead of the names that Qt Designer generates, then you lot can become to the Property Editor and alter the .objectName property to the proper noun that seems right for you lot.

If you run this application, then you'll get the following window on your screen:

That's it! Y'all've created a sample text editor with minimal functionality using Qt Designer. Note that to code this application, you wrote only forty-four lines of Python code, which is substantially less than what you'd need to write to hand code the GUI of an equivalent application from scratch.

Conclusion

When yous create applications in PyQt, yous commonly build a main window and several dialogs. Edifice the GUI of those windows and dialogs can take a lot of fourth dimension if you lot hand code them. Luckily, Qt provides Qt Designer, which is a powerful tool intended to create GUIs fast and productively using a user-friendly graphical interface.

With Qt Designer, you tin can elevate and drop all the required widgets onto an empty form, lay them out, and create your GUIs in almost no fourth dimension. Those GUIs are saved in .ui files that you tin translate into Python code and apply in your applications.

In this tutorial, you learned how to:

  • Install Qt Designer on your system
  • Make up one's mind when to use Qt Designer vs mitt code your GUIs
  • Build the GUI of an application's master window using Qt Designer
  • Create and lay out the GUI of your dialogs with Qt Designer
  • Use Qt Designer's .ui files in your GUI applications

Finally, you put all this knowledge into action past using Qt Designer to create the GUIs of the windows and dialogs required to build a sample text editor awarding. You lot can go all the required code and resources to build this application by clicking the link below: