To create a GUI for your windows and dialogs in PyQt, y'all tin can have two main paths: you lot can utilize Qt Designer, or y'all can paw lawmaking the GUI in plain Python lawmaking. The first path can dramatically improve your productivity, whereas the 2d path puts y'all in full control of your awarding's code.

GUI applications oftentimes consist of a main window and several dialogs. If you're looking to create these graphical components in an efficient and convenient way, then Qt Designer is the tool for you lot. 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 information technology on your system
  • When to use Qt Designer vs hand coding for building your GUIs
  • How to build and lay out the GUI of an awarding'southward master window using Qt Designer
  • How to create and lay out the GUI of your dialogs with Qt Designer
  • How to apply Qt Designer's .ui files in your GUI applications

For a better understanding of the topics in this tutorial, you tin can check out the following resource:

  • Python and PyQt: Building a GUI Desktop Computer
  • Python and PyQt: Creating Menus, Toolbars, and Status Confined
  • PyQt Layouts: Create Professional-Looking GUI Applications

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

Getting Started With Qt Designer

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

Qt Designer as well allows you to preview your GUIs using dissimilar styles and resolutions, connect signals and slots, create menus and toolbars, and more.

Qt Designer is platform and programming language independent. Information technology doesn't produce code in any item programming language, but it creates .ui files. These files are XML files with detailed descriptions of how to generate Qt-based GUIs.

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

Installing and Running Qt Designer

There are several ways to get and install Qt Designer depending on your electric current platform. If you employ Windows or Linux, and so yous can run the following commands from your terminal or control line:

                                                  $                  python3 -m venv ./venv                  $                                    source                  venv/bin/activate                  (venv)                  $                  pip install pyqt5 pyqt5-tools                              

Here, yous 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 different directory according 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 as Debian and Ubuntu, you can likewise install Qt Designer by using the organization packet manager with the following command:

                                                  $                  sudo apt install qttools5-dev-tools                              

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

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

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

If you've already installed Qt Designer using 1 of the options discussed so far, so get ahead and launch the application. You should get the following two windows on your screen:

Qt Designer GUI

The window in the foreground is Qt Designer'due south New Course dialog. The window in the background is Qt Designer's main window. In the adjacent two sections, yous'll learn the nuts of how to utilize these components of the Qt Designer interface.

Using Qt Designer'south New Form Dialog

When you run Qt Designer, you're presented with the application's primary window and the New Course dialog. In this dialog, you can select from v available GUI templates. These templates include options to create dialogs, main windows, and custom widgets:

Template Course Type Widgets Base Class
Dialog with Buttons Lesser Dialog OK and Cancel buttons laid out horizontally on the lesser-right corner QDialog
Dialog with Buttons Correct Dialog OK and Cancel buttons laid out vertically on the tiptop-right corner QDialog
Dialog without Buttons Dialog No QDialog
Master Window Chief Window A card bar at the top and a status bar at the bottom QMainWindow
Widget Widget No QWidget

By default, when y'all run Qt Designer, the New Class dialog appears in the foreground. If it doesn't, then yous can click New on Qt Designer's toolbar. You tin besides click File → New in the principal menu or press Ctrl + N on your keyboard.

In the New Form dialog, you tin select the grade template that yous want to start with and then click Create to generate a new course:

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

Annotation that the first two dialog templates have their own default buttons. These are standard buttons included in a QDialogButtonBox. This course automatically handles the position or gild of buttons across different platforms.

For case, if you use a Abolish push and an OK button, then the standard on Linux and macOS is to display those buttons in this same order. But on Windows, the order of buttons will be swapped, with OK appearing first, followed by Abolish. QDialogButtonBox handles this upshot for you automatically.

Working With Qt Designer'due south Main Window

Qt Designer'due south master window provides a menu bar with options for saving and managing forms, editing forms and changing the edit style, laying out and previewing forms, and also for tuning the application'southward settings and accessing its assistance documentation:

Qt Designer Main Menu

The principal window likewise provides a toolbar that displays unremarkably used options. Yous'll use most of these options when you're editing and laying out your forms. These options are also available in the master menu, specially in the File, Edit, and Form menus:

Qt Designer Toolbar

Qt Designer's chief window besides includes a few dock windows that provide a rich gear up of features and tools:

  • Widget Box
  • Object Inspector
  • Belongings Editor
  • Resources Browser
  • Activity Editor
  • Signal/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 selection at the elevation of the window. You 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 tin can show or hide all the available objects in a category by clicking the handle next to the category label.

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

The Widget Box likewise provides a Scratchpad section at the bottom of the window. In this section, you can group frequently used objects in a separate category. You can fill the Scratchpad category with whatever widget currently placed on a form by dragging and dropping them back onto the Widget Box. You 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 course. The Object Inspector also has a filter box at the top to allow yous to find objects in the tree. You can use the Object Inspector to gear up the proper name and other properties of the course and its widgets. You can also correct-click whatsoever widget to admission a context menu with boosted options:

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

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

The Belongings Editor provides a user-friendly way to access and edit the values of the active object'south properties, such as its name, size, font, icon, and so on. The backdrop listed on the editor will modify depending on which object you lot select on your form.

The properties are listed from top to bottom co-ordinate to course bureaucracy. For example, if y'all select a QPushButton on the form, then 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 show different colors to visually differentiate the underlying class.

Finally, yous take three dock windows that usually appear as tabs in the bottom-correct corner:

  1. Resources Browser provides a quick way of calculation resources, such as icons, translation files, images, and other binary files to your applications.
  2. Activeness Editor provides a fashion to create actions and add together them to your forms.
  3. Signal/Slot Editor provides a mode to connect signals and slots in your forms.

Here are some of the options that these tools provide:

Qt Designer Action Signal Resource

That'due south it! These three dock windows round out the set of tools and options that Qt Designer provides for yous to create and customize the GUIs for your dialogs and windows.

Using Qt Designer vs Hand Coding Your GUIs

With PyQt, you have at least two options for creating the GUI of a window or dialog: Y'all tin apply Qt Designer, or yous tin can hand code the GUI in apparently Python code. Both options have their pros and cons. Sometimes it'south hard to decide when to apply one or the other.

Qt Designer provides a user-friendly graphical interface that allows yous to rapidly create GUIs. This can boost your productivity every bit a developer and shorten your development cycles.

Hand coding your GUIs, on the other manus, tin can requite you much more than command over them. With this approach, adding new components and features doesn't require any extra tools across your code editor or IDE, which can exist quite convenient in some evolution environments.

Whether y'all use Qt Designer or hand code your GUIs is a personal decision. Hither are some general considerations on both approaches:

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

Across these concerns, if you're just starting with PyQt, then Qt Designer can help you discover bachelor widgets, layout managers, base classes, properties and their typical values, and and then on.

One last divergence between using Qt Designer and hand coding a GUI is that you need to run an actress step when using Qt Designer: translating .ui files into Python code.

Building Principal Windows With Qt Designer and Python

With PyQt, you tin build main window–style and dialog-style applications. Main window–style applications often consist of a principal window with a bill of fare bar, one or more toolbars, a central widget, and a condition bar. They tin besides include several dialogs, merely those are independent of the principal window.

Qt Designer enables you to quickly build the GUI of your master windows using the predefined Chief Window template. Once you've created a course based on that template, you'll accept tools to perform the following actions:

  • Creating a chief carte
  • Adding and populating toolbars
  • Laying out widgets

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

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

To salvage your forms, go to File → Save, enter main_window.ui in the Save Form As dialog, select a directory to save the file in, and click Save. You tin also get access to the Salvage Form As dialog past pressing Ctrl + S on your keyboard.

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

Creating the Primary Menu

Qt Designer's Main Window template provides an empty card bar at the top of the course. You can add menus to that carte du jour bar using the Menu Editor. Menus are pull-down lists of options that provide quick access to the awarding'southward options. Go back to Qt Designer and your newly created main window. At the top of the form, you'll see a menu bar with the placeholder text Type Here.

If you lot double-click or press Enter on this placeholder text, and then you tin can type the name of your first menu. To confirm the carte name, just press Enter .

Say you desire to create your own text editor. Typically, this kind of application has a File menu with at least some of the post-obit options:

  • New for creating a new document
  • Open for opening an existing certificate
  • Open Recent for opening recently viewed documents
  • Save for saving a document
  • Exit for exiting the awarding

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

Qt Designer Main Menu Editor

Qt Designer's Bill of fare Editor allows you to add menus to the menu bar in a user-friendly mode. When you enter the name of a carte or card selection, yous tin use an ampersand symbol (&) before a given letter to provide a keyboard accelerator.

For example, if y'all add together an ampersand before the F in the File carte du jour, then you can access this card by pressing Alt + F . Likewise, if y'all add an ampersand before the N in New, then one time yous've launched the File card, you can access the New option past pressing N .

With the Bill of fare Editor, you lot tin also add separators to your menus. This is a practiced way to visually split up bill of fare options and grouping them logically. To add a separator, double-click the Add Separator option at the terminate of the active menu in the Menu Editor. You can remove an existing separator by right-clicking it and then selecting Remove Separator in the context menu. This card as well allows y'all to add new separators.

If y'all need to move a separator to another place in a given carte du jour, then you can drag the separator to the desired position and drib information technology there. A blood-red line volition betoken the position where the separator volition be placed.

You can also add a submenu to a given menu option. To practice this, click the icon on the correct side of the menu option to which you lot want to attach the submenu, just like y'all did with the Open Recent selection in the above example.

To run a preview of your grade, go to Form → Preview, or hit the key combination Ctrl + R on your keyboard.

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

With the Action Editor, y'all tin can fine-melody, update, or fix the following options:

  • The text of the activity, which will be shown on carte options and toolbar buttons
  • The object proper name, which you'll use in your lawmaking to reference the action object
  • The icons that will be shown on your carte du jour options and toolbar buttons
  • The checkable holding of the activeness
  • The keyboard shortcuts, which will provide the user with a quick way to access the action

The final ellipsis (...) in the text of your carte options is a widely used convention for naming options that don't perform an immediate action but launch a popular-up dialog for performing farther deportment.

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

In one case you've downloaded the icons, create a resources directory beside your main_window.ui file and re-create the icons there. Then go back to the Action Editor and add icons to your deportment like this:

Note that your menu options at present brandish an icon on the left margin. This provides actress visual information to your users and helps them find the desired option. At present get ahead and add an Edit menu with the following options:

  • Re-create for copying some text
  • Paste for pasting some text
  • Cut for cutting some text
  • Find and Supersede for finding and replacing text

Next, add together a Help card with an About choice for launching a dialog with full general information well-nigh your text editor. Finally, go to the Property Editor and set the championship of your window to Sample Editor. Later on these additions, your master window should look something like this:

Sample Text Editor Main Menu

With these additions, your sample text editor's main menu is starting to look like the bill of fare of a existent text editor!

Creating a Toolbar

You can add as many toolbars as you lot demand to your primary window's GUI using Qt Designer. To do that, right-click on the course and select Add Tool Bar from the context bill of fare. This adds an empty toolbar at the meridian of the window. Alternatively, yous tin can predefine the toolbar area where yous want to place a given toolbar by selecting Add Tool Bar to Other Expanse:

Qt Designer Create Toolbars

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

Actions can be shared between menu options and toolbar buttons, so in this example, y'all reuse the actions that yous created when yous populated your menus in the preceding section. To populate the toolbar, click on an action on the Activity Editor, then drag and drop it onto the toolbar. Note that by right-clicking on the toolbar, you tin add together separators to visually divide the tool buttons.

Laying Out a Unmarried 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, one or more toolbars, ane or more dock widgets, a status bar, and a central widget. By default, Qt Designer uses a QWidget object as the primal widget on the Main Window template.

Using a bare-bones QWidget object equally the key widget on a main window'due south GUI is a good pick because, on summit of that widget, you lot can place either a single widget or multiple widgets in a coherent layout.

For example, in your sample text editor, you might want to utilise a unmarried widget that provides your users with a work expanse to type, copy, paste, and edit their text. For this purpose, you tin employ a QTextEdit object and then add together a vertical (or horizontal) layout as the fundamental widget's layout:

In this example, you offset elevate a QTextEdit onto the form. Then y'all click on the form to select your key widget. Finally, y'all apply a vertical layout to your central widget past clicking Lay Out Vertically on Qt Designer'southward toolbar.

Since the spacing around the QTextEdit doesn't look right, y'all 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 accommodate your widgets rapidly. Arguably, the well-nigh accessible fashion of laying out your GUIs with Qt Designer is using the layout-related department on the principal toolbar:

Qt Designer Layout Toolbar

From left to right, you lot'll find the following options to create different types of layouts:

Option Widget System Layout Grade Keyboard Shortcut
Lay Out Horizontally Horizontally in ane 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 + iii
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 Form Layout Tabularly in a two-column tabular array QFormLayout Ctrl + six

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

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

  2. Conform Size adjusts the size of the layout to accommodate contained widgets and to ensure that each has plenty space to be visible. To access this selection, you can press Ctrl + J on your keyboard.

You can also access all these layout-related options through Qt Designer's main menu bar, under the Form menu:

Qt Designer Form Menu

In the Form menu, you have 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 form'southward context menu, nether the Lay Out selection.

Laying Out a Compound Fundamental Widget

When you're creating your main windows, you might face situations in which you need to use multiple widgets in a given layout as your fundamental widget. Since Qt Designer's Master Window template ships with a QWidget object as its central widget, you can take advantage of this to create your own custom arrangement of widgets and so set up it equally the top-level layout of that central widget.

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

  1. Elevate and drib the widgets onto your course and try to identify them almost their desired position.
  2. Select the widgets that should exist managed together by a given layout.
  3. Apply the appropriate layout using Qt Designer's toolbar or main menu, or with the form's context menu.

Although yous tin can elevate layouts onto a form and so elevate widgets onto the layouts, the best practise is to drag all the widgets and spacers first and then repeatedly select related widgets and spacers to employ layouts to them.

For example, suppose y'all're building a calculator awarding. You demand a QLineEdit object on the pinnacle of your form to display the operations and their results. Under the line edit, yous 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, merely the GUI is messy and cluttered. To conform this into a more than polished reckoner GUI, yous can use a grid layout for the buttons and a vertical box layout as the calculator's summit-level layout:

Your calculator yet needs some extra polishing, but information technology looks a lot meliorate at present. To get a more 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 lot can as well fix a fixed size for your calculator's main window, and so on. Go alee and give it a endeavor!

Having a Status Bar

Qt Designer'south Main Window template provides a condition bar by default. A status bar is a horizontal panel that's usually placed at the bottom of the principal window in a GUI application. Its primary purpose is to display information about the electric current status of the application.

You tin can divide a status bar into several sections and show different information on each department. The information on the status bar tin can be temporary or permanent, and most of the time information technology comes equally text messages. The purpose of the information displayed on the status bar is to keep your users updated about what the application is currently doing and what its general condition is at a given fourth dimension.

You lot tin can also use the condition bar to brandish help tips, which are short aid messages that describe what a given push or carte option does. This kind of message appears on the condition bar when the user hovers the mouse pointer over a toolbar button or carte option.

Creating a Dialog With Qt Designer and Python

Dialogs are pocket-sized-sized windows that you lot commonly use to provide auxiliary functionalities, such as a Preferences dialog, or to communicate with your users by showing error messages or full general information about a given operation. Yous tin can also use dialogs to ask the user for some required information or to ostend an performance that's about to take place.

PyQt offers a rich prepare of built-in dialog that you can use in your applications directly. You but need to import them from PyQt5.QtWidgets. Here's a summary:

All these built-in dialogs are ready for you lot to use in your lawmaking straight. Most of them provide form methods to build specific types of dialogs depending on your needs. Along with these dialogs, PyQt provides the QDialog grade. You tin utilise this class to create your own dialogs in code, but you lot can as well use Qt Designer to create your dialogs chop-chop.

In the next few sections, you'll larn 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 appropriate template for the dialog from the New Class dialog. Drag and driblet the required widgets onto the form, lay out them correctly, and save the course in a .ui file for afterwards use in your awarding.

Go back to your sample text editor and suppose yous want to add together a Observe 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 form:

Here, yous first create an empty dialog using the Dialog without Buttons template and set the window title to Detect and Supercede in the Object Inspector. So you lot drag and drib 2 QLabel objects onto the course using the Widget Box. These labels ask the users for the words they need to observe and supersede. Those words will exist entered in the corresponding QLineEdit objects nigh the labels.

Next, yous drag and drop iii QPushButton objects onto the course. These buttons volition allow your users to observe and replace words in their current certificate. Finally, you lot add two QCheckBox objects to provide Friction match Instance and Match Whole Word options.

Once you accept all the widgets on the form, make sure to place them in a position that'southward similar to what you want to reach in your final dialog. At present it's time to lay out the widgets.

Laying Out the Dialog GUI

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

Here, you lot select the labels, line edits, and checkboxes with your mouse arrow and apply a grid layout to them. After that, you add a vertical spacer between the Supersede and Cancel buttons to proceed them visually separated.

The final step is to set the dialog'due south height-level layout. In this case, y'all apply a horizontal layout director. That's it! You've built the GUI of your Discover and Supercede dialog with Qt Designer. Save it with the filename find_replace.ui.

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

Connecting Signals and Slots

So far, y'all've used Qt Designer in the Edit Widgets fashion, which is its default mode. In this mode, you can add widgets to your forms, edit widget's properties, lay out the widgets on the grade, and so on. Withal, Qt Designer has up to four different modes to allow yous to work on dissimilar features of your forms:

Way Purpose Menu Pick Keyboard Shortcut
Edit Widgets Editing widgets Edit → Edit Widgets F3
Edit Signals/Slots Connecting congenital-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 gild of widgets Edit → Edit Tab Society No

You can also access these modes by clicking their corresponding buttons in the mode-related department of Qt Designer's toolbar, which looks like this:

Qt Designer Mode Toolbar

To be able to edit the built-in signals and slots of your widgets and forms, you kickoff need to switch to the Edit Signals/Slots mode.

User actions on widgets and forms, such equally a click or a keypress, are known every bit events in PyQt. When an event occurs, the widget at mitt emits a signal. This mechanism allows y'all 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 issue, you need to select one of the signals emitted by the widget in response to an event and connect it to the desired slot.

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

To establish a signal-and-slot connection between two widgets using Qt Designer, y'all need to select the bespeak-provider widget with your mouse and and so drag and drop it over the slot-provider widget. This launches Qt Designer's Configure Connection dialog. Now go back to the Find and Replace dialog and switch to Qt Designer'southward Edit Signals/Slots mode. Then drag and drop the Cancel button onto the form:

Qt Designer Configure Connection Dialog

The Configure Connectedness dialog has ii panels. On the left console, you can select a point from the signal-provider widget, and on the right panel, you tin select a slot from the slot-provider widget. To create the connexion, press OK:

Qt Designer Create Connection

The connection appears as an arrow from the signal-provider widget to the slot-provider widget, indicating that the connection is established. You lot'll also see the proper noun of the point and the slot that you lot merely connected.

In this instance, you continued the clicked() bespeak of the Cancel push button with the turn down() slot of the dialog. Now when you click Cancel, your action volition exist ignored, and the dialog will close.

To modify a connection, double-click the arrow or ane of the labels. This displays the Configure Connexion dialog, in which you tin can modify the indicate or the slot involved in the connectedness co-ordinate to your needs.

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

Setting the Tab Lodge of Widgets

To improve the usability of your dialogs, y'all tin fix a coherent tab society for your input widgets. The tab gild is the order in which the widgets on your form come up into focus when you press Tab or Shift + Tab on your keyboard.

If yous're using Qt Designer to create your forms, and then the default tab order of your widgets is based on the society in which you place each widget on the course. Sometimes this order isn't right, and when you hit Tab or Shift + Tab , the focus jumps to an unexpected widget. Have a expect at the tab order beliefs in your Find and Replace dialog:

Find Replace Dialog Tab Order

The focus starts on the Find line edit, then information technology goes through the Supplant line edit, so through the checkboxes, and finally through the buttons. What if you want the focus to jump from the Find line edit to the Replace line edit so to the Find push? In this case, you can change the tab order of the input widgets on the dialog. Switch to Edit Tab Social club manner in Qt Designer. Y'all'll run across something like this:

Qt Designer Tab Order

In Edit Tab Club mode, each input widget in the form shows a number that identifies its position in the tab-order concatenation. You can change that order past clicking on the numbers in the desired order:

Qt Designer Change Tab Order

You change the tab order of the input widgets by clicking the numbers in the desired club. Note that when you select a number, it changes to carmine, indicating that this is the currently edited position in the tab-club concatenation. Numbers you oasis't set are shown in blue, and the numbers you take set are shown in light-green. If you brand a mistake, then y'all can restart the ordering by choosing Restart from the form's context carte.

Providing Keyboard Accelerators

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

To define a keyboard accelerator on a widget that includes a label, such as a push or a checkbox, yous just need to place an ampersand symbol (&) earlier the letter of the alphabet in the characterization text that you want to utilise in the accelerator. For case, place an ampersand earlier the C on the Cancel button of your Notice and Replace dialog, run a preview, and press Alt + C like in the following case:

Qt Designer Set Accelerator

By placing an ampersand earlier the letter C in the text of the Cancel button, y'all create a keyboard accelerator. If you lot press Alt + C on your keyboard, then the Cancel push 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 lot need to make that widget a buddy of a characterization object. At that place are iv steps that you need to take if you lot desire to create a buddy connection:

  1. Select a letter in the text of the label to identify the buddy connectedness and provide the keyboard accelerator.
  2. Place an ampersand (&) before the selected letter of the alphabet in the text of the characterization.
  3. Switch to Edit Buddies mode in Qt Designer.
  4. Drag and drop the label onto the buddy widget.

Here's how you tin can create a buddy relationship between the Find label and its related line edit:

Qt Designer Set Buddies

To create a buddy relationship betwixt a label and a widget, select the label with your mouse and drag information technology onto the input widget that yous want to set as its buddy. The label and the input widget volition become buddies. From this point on, you can press Alt plus the selected letter in the characterization text to move the focus to the related widget.

It's important to note that y'all shouldn't have 2 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.

Go ahead and use Qt Designer to set keyboard accelerators for the widgets on your Find and Supersede dialog. The final issue should look 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 primary windows and dialogs with Qt Designer. In this department, y'all'll larn how to integrate those GUIs into your Python code and build a real application. There are 2 chief approaches to do that in PyQt:

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

The beginning arroyo uses pyuic5, which is a tool included in the PyQt installation that allows you to translate the content of a .ui file into Python lawmaking. This arroyo is widely used because of its efficiency. However, it has 1 drawback: every fourth dimension y'all modify the GUI with Qt Designer, you lot need to generate the code again.

The 2nd approach takes advantage of uic.loadUi() to dynamically load the content of a .ui file into your application. This approach is suitable when you're working with pocket-sized GUIs that don't involve substantial loading time.

Setting Upwardly Windows and Dialogs for Utilise

At present it's time to fix upwards your windows and dialogs for utilize in a real application (in this case, a sample text editor). If you've been post-obit this tutorial, then yous should have at least ii .ui files:

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

Go ahead and create a new directory called sample_editor/. Within this directory, create another directory called ui/ and re-create your .ui files into it. Also, copy the resources/ directory that contains the icons for your menu options and toolbar buttons to the sample_editor/ui/ directory. So far, the structure of your application should look similar this:

                                sample_editor/ │ └── ui/     ├── resource/     │   ├── edit-re-create.png     │   ├── edit-cut.png     │   ├── edit-paste.png     │   ├── file-exit.png     │   ├── file-new.png     │   ├── file-open.png     │   ├── file-save.png     │   └── help-content.png     │     ├── find_replace.ui     └── main_window.ui                              

Since the main-window GUI is relatively circuitous, you can use pyuic5 to translate the content of main_window.ui into Python lawmaking.

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

Now open up a final and navigate to the sample_editor/ directory. In one case you're there, run the post-obit 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 it in your sample_editor/ directory. This module contains the Python code for your principal window's GUI. Here's a minor sample of the code:

                                                  # -*- coding: utf-eight -*-                  # Class implementation generated from reading ui file 'ui/main_window.ui'                  #                  # Created past: PyQt5 UI code generator 5.fifteen.1                  #                  # Alarm: Any manual changes fabricated to this file will be lost when pyuic5 is                  # run once again.  Do not edit this file unless you know what you are doing.                  from                  PyQt5                  import                  QtCore                  ,                  QtGui                  ,                  QtWidgets                  class                  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'south main window. Note that .setupUi() contains the code to create all the required widgets and lay them out on the GUI. .retranslateUi() contains lawmaking for internationalization and localization, just this topic is across the telescopic of this tutorial.

At present your working directory should await like this:

                                sample_editor/ │ ├── ui/ │   ├── resources/ │   │   ├── edit-copy.png │   │   ├── edit-cutting.png │   │   ├── edit-paste.png │   │   ├── file-exit.png │   │   ├── file-new.png │   │   ├── file-open.png │   │   ├── file-save.png │   │   └── assistance-content.png │   │ │   ├── find_replace.ui │   └── main_window.ui │ └── main_window_ui.py                              

Since your Observe and Replace dialog is quite pocket-size, you tin can load its GUI directly from your .ui file using uic.loadUi(). This function takes a string with the path to a .ui file as an argument and returns a QWidget subclass that implements the GUI.

This manner of loading .ui files dynamically is rarely used in practice. You can use it with minor dialogs that don't require besides much endeavor to load. With this approach, you don't need to generate the Python code for the dialog'south GUI every time y'all modify the .ui file with Qt Designer, which tin be a productivity and maintainability win in some cases.

Now that y'all've chosen a strategy for edifice each of your GUIs, information technology'southward time to put everything together in a real application.

Putting Everything Together in an Application

With all the pieces in place for your sample text editor, you tin create the application and write the required code to use the master window and the Observe and Replace dialog. Burn down up your favorite code editor or IDE in your sample_editor/ directory and create a new file chosen app.py. Add together the following lawmaking to information technology:

                                                                      1                  import                  sys                                      two                                      3                  from                  PyQt5.QtWidgets                  import                  (                                      4                  QApplication                  ,                  QDialog                  ,                  QMainWindow                  ,                  QMessageBox                                      v                  )                                      6                  from                  PyQt5.uic                  import                  loadUi                                      7                                      8                  from                  main_window_ui                  import                  Ui_MainWindow                                      9                  10                  class                  Window                  (                  QMainWindow                  ,                  Ui_MainWindow                  ):                  11                  def                  __init__                  (                  self                  ,                  parent                  =                  None                  ):                  12                  super                  ()                  .                  __init__                  (                  parent                  )                  xiii                  self                  .                  setupUi                  (                  cocky                  )                  fourteen                  self                  .                  connectSignalsSlots                  ()                  15                  16                  def                  connectSignalsSlots                  (                  cocky                  ):                  17                  self                  .                  action_Exit                  .                  triggered                  .                  connect                  (                  self                  .                  close                  )                  18                  self                  .                  action_Find_Replace                  .                  triggered                  .                  connect                  (                  self                  .                  findAndReplace                  )                  nineteen                  cocky                  .                  action_About                  .                  triggered                  .                  connect                  (                  self                  .                  about                  )                  20                  21                  def                  findAndReplace                  (                  cocky                  ):                  22                  dialog                  =                  FindReplaceDialog                  (                  cocky                  )                  23                  dialog                  .                  exec                  ()                  24                  25                  def                  about                  (                  cocky                  ):                  26                  QMessageBox                  .                  about                  (                  27                  cocky                  ,                  28                  "About Sample Editor"                  ,                  29                  "<p>A sample text editor app built 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"                  ,                  cocky                  )                  39                  xl                  if                  __name__                  ==                  "__main__"                  :                  41                  app                  =                  QApplication                  (                  sys                  .                  argv                  )                  42                  win                  =                  Window                  ()                  43                  win                  .                  show                  ()                  44                  sys                  .                  leave                  (                  app                  .                  exec                  ())                              

Here's what this lawmaking does:

  • Line three imports the required PyQt classes to build the application and the GUI.
  • Line 6 imports loadUi() from the uic module. This office provides a way of loading the content of a .ui file dynamically.
  • Line 8 imports Ui_MainWindow, which contains the GUI for your master window.
  • Line x defines Window, which will provide your awarding'south principal window. In this case, the course uses multiple inheritance. It inherits the principal window functionality from QMainWindow and the GUI functionality from Ui_MainWindow.
  • Line 13 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 example of your Discover and Replace dialog and execute it.
  • Line 25 defines .about(), which creates and launches a small dialog to provide information nigh the application. In this example, yous employ a built-in dialog based on QMessageBox.
  • Line 35 defines FindReplaceDialog, which provides the Detect and Supervene upon dialog.
  • Line 38 calls loadUi() to load the dialog'due south GUI from the files ui/find_replace.ui.

Finally, on lines 41 to 44, you create the awarding, create and evidence the main window, and run the awarding'southward main loop by calling .exec() on the awarding object.

It'south important to notation that Qt Designer can name your actions a bit differently from what you saw in the above lawmaking. For example, you might find the name .actionE_xit instead of .action_Exit to refer to the Go out action. So, for this example to work properly, you need to make sure you're using the right names.

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

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

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

Conclusion

When y'all create applications in PyQt, you commonly build a principal window and several dialogs. Building the GUI of those windows and dialogs tin can have a lot of time 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 convenient graphical interface.

With Qt Designer, yous can drag 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 lot tin can interpret into Python code and use in your applications.

In this tutorial, yous learned how to:

  • Install Qt Designer on your system
  • Decide when to use Qt Designer vs hand code your GUIs
  • Build the GUI of an awarding's main 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 noesis into action by using Qt Designer to create the GUIs of the windows and dialogs required to build a sample text editor awarding. You can get all the required code and resources to build this application by clicking the link below: