Python qt designer windows

Qt Designer is a cross-platform drag and drop GUI designer, which can be used to build UIs for both PyQt and PySide.
It is a great tool to simplify the process of building interfaces for your applications.

While Qt Designer is distributed by Qt as part of the Qt Creator integrated IDE, most of that IDE is not useful or helpful
for Python development — primarily being designed for C++ developers. If you just want the Designer application, this is
not currently available from Qt. But helpfully, other people have stepped up to make this available.

In this guide we’ll look at the various options available for installing Qt Designer as a standalone application on your system.

Since the Qt Designer software is free software, these alternative distributions of Qt Designer are permitted.

PyQt Command line launcher

Qt Designer is available on PyPi via the pyqt5-tools package. This can be pip installed just like any other Python package.
This wrapper will download and install Qt Designer for you and provide a command-line launcher to start the program.

  • PyQt6
  • PyQt5

bash

pip install pyqt6-tools

bash

pip install pyqt5-tools

After installation you can run Qt Designer from the command line using the built-in launcher.

  • PyQt6
  • PyQt5

If this doesn’t work check your Python scripts folder is in your PATH.

Over 10,000 developers have bought Create GUI Applications with Python & Qt!

[[ discount.discount_pc ]]% OFF for
the next [[ discount.duration ]]
[[discount.description ]]
with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses
with code [[ discount.coupon_code ]]

PySide6 Command line launcher

In recent versions of PySide6 Qt Designer is installed automatically when you install PySide6 with pip. After installation you can
run Qt Designer from the command line using the built-in launcher.

If this doesn’t work check your Python scripts folder is in your PATH.

Installing from Qt Package

If the above installation options don’t work for you, you can instead follow the following instructions to install
Qt Creator or Qt Designer depending on your platform.

If you install Qt Creator you can access Qt Designer through it, even if you don’t use any of the other functionality.

Windows

Qt Designer is available in the installation packages for Qt available from the Qt downloads page. Download and run the appropriate installer for your system and follow the platform-specific instructions below. Installing Qt Designer will not affect your Python PyQt5/6 or PySide2/6 installation.

Qt Designer is not mentioned in the Windows Qt installer, but is automatically installed when you install any version of the Qt core libraries. For example, in the following screenshot we’ve opted to install the MSVC 2017 64-bit version of Qt — what you choose will have no effect on your Designer install.

Installing Qt, will also install Qt Designer.

Installing Qt, will also install Qt Designer.

If you want to install Qt Creator it is listed under «Developer and Designer Tools». Rather confusingly, Qt Designer isn’t in here.

Installing the Qt Creator component.

Installing the Qt Creator component.

macOS

Qt Designer is available in the installation packages for Qt available from the Qt downloads page. Download and run the appropriate installer for your system and follow the platform-specific instructions below. Installing Qt Designer will not affect your Python PyQt5/6 or PySide2/6 installation.

Qt Designer is not mentioned in the macOS Qt installer, but is automatically installed when you install any version of the Qt core libraries. Download the installer from the Qt website — you can opt for the open source version.

Inside the downloaded .dmg file you'll find the installer.

Inside the downloaded .dmg file you’ll find the installer.

Open the installer to start the installation. Go through to where it asks you to choose which components to install. Select the macOS package under the latest version of Qt.

You only need the macOS package under the latest version.

You only need the macOS package under the latest version.

Once the installation is complete, open the folder where you installed Qt. The launcher for Designer is under <version>/clang_64/bin. You’ll notice that Qt Creator is also installed in the root of the Qt installation folder.

You can find the Designer launcher under the <version>/clang_64/bin folder.» height=»1138″ loading=»lazy» src=»https://www.pythonguis.com/static/installation/installation-designer/installation-mac-launch.png» srcset=»https://ik.imagekit.io/mfitzp/pythonguis/static/installation/installation-designer/installation-mac-launch.png?tr=w-100 100w, https://ik.imagekit.io/mfitzp/pythonguis/static/installation/installation-designer/installation-mac-launch.png?tr=w-200 200w, https://ik.imagekit.io/mfitzp/pythonguis/static/installation/installation-designer/installation-mac-launch.png?tr=w-400 400w, https://ik.imagekit.io/mfitzp/pythonguis/static/installation/installation-designer/installation-mac-launch.png?tr=w-600 600w» width=»2784″></p>
<div class= Картинка с сайта: www.pythonguis.com

You can find the Designer launcher under the /clang_64/bin folder.

You can run Designer from where it is located, or move it into your Applications folder so it is available to launch from the macOS Launchpad.

Linux (Ubuntu & Debian)

You can install Qt Designer using your package manager. Depending on your distribution and version you will have either
Qt5 Designer or Qt6 Designer available..

  • Qt5
  • Qt6

bash

sudo apt-get install qttools5-dev-tools

bash

sudo apt-get install designer-qt6

Once installed, Qt Designer will be available in the launcher.

Qt Designer in Ubuntu launcher.

Qt Designer in Ubuntu launcher.

To create a GUI for your windows and dialogs in PyQt, you can take two main paths: you can use Qt Designer, or you can hand code the GUI in plain Python code. The first path can dramatically improve your productivity, whereas the second path puts you in full control of your application’s code.

GUI applications often consist of a main window and several dialogs. If you’re looking to create these graphical components in an efficient and user-friendly way, 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’ll learn:

  • What Qt Designer is and how to install it 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 application’s main window using Qt Designer
  • How to create and lay out the GUI of your dialogs with Qt Designer
  • How to use Qt Designer’s .ui files in your GUI applications

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

  • Python and PyQt: Building a GUI Desktop Calculator
  • Python and PyQt: Creating Menus, Toolbars, and Status Bars
  • 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 get the code and all the required resources 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-see-is-what-you-get (WYSIWYG) user interface to create GUIs for your PyQt applications productively and efficiently. With this tool, you create GUIs by dragging and dropping QWidget objects on an empty form. After that, you can arrange them into a coherent GUI using different layout managers.

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

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

You can translate the content of .ui files into Python code with pyuic5, which is a command-line tool that comes with PyQt. Then you can use this Python code in your GUI applications. You can also 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 current platform. If you use Windows or Linux, then you can run the following commands from your terminal or command line:

Here, you 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 also install Qt Designer by using the system package manager with the following command:

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 be able to run Qt Designer by 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 you should have Qt Designer already installed on your system.

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

If you’ve already installed Qt Designer using one of the options discussed so far, then go 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’s New Form dialog. The window in the background is Qt Designer’s main window. In the next two 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’re presented with the application’s main window and the New Form dialog. In this dialog, you can select from five available 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 bottom-right corner QDialog
Dialog with Buttons Right Dialog OK and Cancel buttons laid out vertically on the top-right corner QDialog
Dialog without Buttons Dialog No QDialog
Main Window Main 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 it doesn’t, then you can click New on Qt Designer’s toolbar. You can also click File → New in the main menu or press Ctrl+N on your keyboard.

In the New Form dialog, you can select the form template that you want to start with and then click Create to generate a new form:

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 then click Create or press Alt+R on your keyboard.

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

For example, if you use a Cancel button 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 Cancel. QDialogButtonBox handles this issue 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 use most of these options when you’re editing and laying out your forms. These options are also available in the main menu, especially in the File, Edit, and Form menus:

Qt Designer Toolbar

Qt Designer’s main window also includes a few dock windows that provide a rich set of features and tools:

  • Widget Box
  • Object Inspector
  • Property Editor
  • Resource Browser
  • Action 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 option at the top 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 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 pointer and then drag and drop them onto the form 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 can fill the Scratchpad category with any 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 right-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 also has a filter box at the top to allow you to find objects in the tree. You can use the Object Inspector to set the name and other properties of the form and its widgets. You can also right-click any 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-child relationship of the widgets and objects on the current form.

The Property Editor is another dock window that appears in Qt Designer’s main window. This window holds a two-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, as the name implies:

The Property 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, and so on. The properties listed on the editor will change depending on which object you select on your form.

The properties are listed from top to bottom according to class hierarchy. For example, if you 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, you have three dock windows that commonly appear as tabs in the bottom-right corner:

  1. Resource Browser provides a quick way of adding resources, such as icons, translation files, images, and other binary files to your applications.
  2. Action Editor provides a way to create actions and add them to your forms.
  3. Signal/Slot Editor provides a way 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 it! These three dock windows round out the set 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 Hand Coding Your GUIs

With PyQt, you have at least two options for creating the GUI of a window or dialog: You can use Qt Designer, or you can hand code the GUI in plain Python code. Both options have their pros and cons. Sometimes it’s hard to decide when to use one or the other.

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

Hand coding your GUIs, on the other hand, can give you much more control over them. With this approach, adding new components and features doesn’t require any extra tools beyond your code editor or IDE, which can be quite convenient in some development environments.

Whether you use Qt Designer or hand code your GUIs is a personal decision. Here are some general considerations on both approaches:

Feature Qt Designer Hand Coding
Developer’s productivity High High 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 Low High
Amount of boilerplate code High Low

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

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

Building Main Windows With Qt Designer and Python

With PyQt, you can build main window–style and dialog-style applications. Main window–style applications often consist of a main window with a menu bar, one or more toolbars, a central widget, and a status bar. They can also include several dialogs, but those are independent of the main window.

Qt Designer enables you to quickly build the GUI of your main windows using the predefined Main Window template. Once you’ve created a form based on that template, you’ll have tools to perform the following actions:

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

Qt Designer’s 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 later recreate the GUI in your applications.

To save 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 can also get access to the Save Form As 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 main window you just created.

Creating the Main Menu

Qt Designer’s Main Window template provides an empty menu bar at the top of the form. You can add menus to that menu bar using the Menu Editor. Menus are pull-down lists of options that provide quick access to the application’s 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 double-click or press Enter on this placeholder text, then you can type the name of your first menu. To confirm the menu name, just press Enter.

Say you want to create your own text editor. Typically, this kind of application 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
  • Save for saving a document
  • Exit for exiting the application

Here’s how you can use Qt Designer to create this menu:

Qt Designer’s Menu Editor allows you to add menus to the menu bar in a user-friendly way. When you enter the name of a menu or menu option, you can use an ampersand symbol (&) before a given letter to provide a keyboard accelerator.

For example, if you add an ampersand before the F in the File menu, then you can access this menu by pressing Alt+F. Likewise, if you add an ampersand before the N in New, then once you’ve launched the File menu, you can access the New option by pressing N.

With the Menu Editor, you can also add separators to your menus. This is a good way to visually separate menu options and group them logically. To add a separator, double-click the Add Separator option at the end 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 menu also allows you to add new separators.

If you need to move a separator to another place in a given menu, then you can drag the separator to the desired position and drop it there. A red line will indicate the position where the separator will be placed.

You can also add a submenu to a given menu option. To do this, click the icon on the right side of the menu option to which you want to attach the submenu, just like you did with the Open Recent option in the above example.

To run a preview of your form, go to Form → Preview, or hit the key 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, you create an action. 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-tune your actions:

With the Action Editor, you can fine-tune, update, or set the following options:

  • The text of the action, which will be shown on menu options and toolbar buttons
  • The object name, 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 way to access the action

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

In the case of the icons, you need to pack those icons with your application as 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 resources directory beside your main_window.ui file and copy the icons there. Then get back to the Action Editor and add icons to your actions like this:

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

  • Copy for copying some text
  • Paste for pasting some text
  • Cut for cutting some text
  • Find and Replace for finding and replacing text

Next, add a Help menu with an About option for launching a dialog with general information about your text editor. Finally, go to the Property Editor and set the title of your window to Sample Editor. After these additions, your main 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 menu of a real text editor!

Creating a Toolbar

You can add as many toolbars as you need to your main window’s GUI using Qt Designer. To do that, right-click on the form and select Add Tool Bar from the context menu. This adds an empty toolbar at the top of the window. Alternatively, you can predefine the toolbar area where you want to place a given toolbar by selecting Add Tool Bar to Other Area:

Qt Designer Create Toolbars

Once you have your toolbars in place, you 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 Action Editor:

Actions can be shared between menu options and toolbar buttons, so in this case, you reuse the actions that you created when you populated your menus in the preceding section. To populate the toolbar, click on an action on the Action Editor, then drag and drop it onto the toolbar. Note that by right-clicking on the toolbar, you can add separators to visually separate 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, one or more toolbars, one or more dock widgets, a status bar, and a central widget. By default, Qt Designer uses a QWidget object as the central widget on the Main Window template.

Using a bare-bones QWidget object as the central widget on a main window’s GUI is a good choice because, on top 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 might want to use a single widget that provides your users with a work area to type, copy, paste, and edit their text. For this purpose, you can use 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. Then you click on the form to select your central widget. Finally, you apply a vertical layout to your central widget by clicking Lay Out Vertically on Qt Designer’s toolbar.

Since the spacing around 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 can use different layout managers to arrange your widgets quickly. Arguably, the most accessible way of laying out your GUIs with Qt Designer is using the layout-related section on the main toolbar:

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

Option Widget Arrangement Layout Class Keyboard Shortcut
Lay Out Horizontally Horizontally in one row and several columns QHBoxLayout Ctrl+1
Lay Out Vertically Vertically in one 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 Form 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 you to break an existing layout. Once widgets are arranged in a layout, you can’t move or resize them individually because their geometry is controlled by the layout. To modify individual widgets, you might need to break the layout and redo it later. To access this option, you can press Ctrl+0 on your keyboard.

  2. Adjust Size adjusts the size of the layout to accommodate contained widgets and to ensure that each has enough space to be visible. To access this option, 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:

In the Form menu, you have access to all the layout-related options, with a complete reference of the keyboard shortcuts to access them. You can also access these options through the form’s context menu, under the Lay Out option.

Laying Out a Compound Central 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 central widget. Since Qt Designer’s Main 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 then set it as the top-level layout of that central widget.

With Qt Designer, you can 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, then you can build it by running the following steps:

  1. Drag and drop the widgets onto your form and try to place them near their desired position.
  2. Select the widgets that should be 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 you can drag layouts onto a form and then drag widgets onto the layouts, the best practice is to drag all the widgets and spacers first and then repeatedly select related widgets and spacers to apply layouts to them.

For example, suppose you’re building a calculator application. You need a QLineEdit object on the top of your form 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, but the GUI is messy and cluttered. To arrange this into a more polished calculator GUI, you can use a grid layout for the buttons and a vertical box layout as the calculator’s top-level layout:

Your calculator still needs some extra polishing, but it looks a lot better now. 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 can also set a fixed size for your calculator’s main window, and so on. Go ahead and give it a try!

Having a Status Bar

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

You can divide a status bar into several sections and show different information on each section. The information on the status bar can be temporary or permanent, and most of the time it comes as 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 status is at a given time.

You can also use the status bar to display help tips, which are short help messages that describe what a given button or menu option does. This kind of message appears on the status bar when the user hovers the mouse pointer over a toolbar button or menu option.

Creating a Dialog With Qt Designer and Python

Dialogs are small-sized windows that you commonly use to provide auxiliary functionalities, such as a Preferences dialog, or to communicate with your users by showing error messages or general information about a given operation. You can also use dialogs to ask the user for some required information or to confirm an operation that’s about to take place.

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

All these built-in dialogs are ready for you 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 class. You can use this class to create your own dialogs in code, but you can also use Qt Designer to create your dialogs quickly.

In the next few sections, you’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 appropriate template for the dialog from the New Form dialog. Drag and drop the required widgets onto the form, lay out them correctly, and save the form in a .ui file for later use in your application.

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

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

Here, you first create an empty dialog using the Dialog without Buttons template and set the window title to Find and Replace in the Object Inspector. Then you drag and drop two QLabel objects onto the form using the Widget Box. These labels ask the users for the words they need to find and replace. Those words will be entered in the corresponding QLineEdit objects near the labels.

Next, 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 two QCheckBox objects to provide Match Case and Match Whole Word options.

Once you have all the widgets on the form, make sure to place them in a position that’s similar to what you want to achieve in your final dialog. Now it’s time to lay out the widgets.

Laying Out the Dialog GUI

As you saw before, to arrange the widgets in a form, you 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 select the labels, line edits, and checkboxes with your mouse pointer and apply a grid layout to them. After that, you add a vertical spacer between the Replace and Cancel buttons to keep them visually separated.

The final step is to set the dialog’s top-level layout. In this case, you use a horizontal layout manager. That’s it! You’ve built 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 can set the tab order of your input widget to improve the experience of users navigating your dialogs with their keyboard. You can also provide keyboard accelerators, connect signals and slots, and so on.

Connecting Signals and Slots

So far, you’ve used Qt Designer in the Edit Widgets mode, 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 form, and so on. However, Qt Designer has up to four different modes to allow you to work on different features of your forms:

Mode 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 order of widgets Edit → Edit Tab Order No

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

To be able to edit the built-in 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 as a click or a keypress, are known as events in PyQt. When an event occurs, the widget at hand emits a signal. This mechanism allows you 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 event, 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 built-in signals that are emitted when a given event occurs on the widget. Widgets also 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, you need to select the signal-provider widget with your mouse and then 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’s Edit Signals/Slots mode. Then drag and drop the Cancel button onto the form:

Qt Designer Configure Connection Dialog

The Configure Connection dialog has two panels. On the left panel, you can select a signal from the signal-provider widget, and on the right panel, you can select a slot from the slot-provider widget. To create the connection, 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’ll also see the name of the signal and the slot that you just connected.

In this case, you connected the clicked() signal of the Cancel button with the reject() slot of the dialog. Now when you click Cancel, your action will be ignored, and the dialog will close.

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

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

Setting the Tab Order of Widgets

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

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

Find Replace Dialog Tab Order

The focus starts on the Find line edit, then it goes through the Replace line edit, then 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 and then to the Find button? In this case, you can change the tab order of the input widgets on the dialog. Switch to Edit Tab Order mode in Qt Designer. You’ll see something like this:

Qt Designer Tab Order

In Edit Tab Order mode, each input widget in the form shows a number that identifies its position in the tab-order chain. You can change that order by 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 order. Note that when you select a number, it changes to red, indicating that this is the currently edited position in the tab-order chain. Numbers you haven’t set are shown in blue, and the numbers you have set are shown in green. If you make a mistake, then you can restart the ordering by choosing Restart from the form’s context menu.

Providing Keyboard Accelerators

A keyboard accelerator is a key combination that you 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 key and a letter that identifies the widget or option that you want to access. This can help you improve the usability of your applications.

To define a keyboard accelerator on a widget that includes a label, such as a button or a checkbox, you just need to place an ampersand symbol (&) before the letter in the label text that you want to use in the accelerator. For example, place an ampersand before the C on the Cancel button 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 before the letter C in the text of the Cancel button, you create a keyboard accelerator. If you press Alt+C on your keyboard, then the Cancel button is selected and the dialog closes.

To define a keyboard accelerator on a widget that doesn’t include a label, such as a line edit, you need to make that widget a buddy of a label object. There are four steps that you need to take if you want 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. Place an ampersand (&) before the selected letter 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’s how you can create a buddy relationship between 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 set as its buddy. The label and the input widget will become buddies. From this point on, you can press Alt plus the selected letter in the label text to move the focus to the related widget.

It’s important to note that you shouldn’t have two widgets with the same keyboard accelerator in a given form. This means that you need to select a unique letter for each keyboard accelerator.

Go ahead and use Qt Designer to set keyboard accelerators for the widgets on your Find and Replace dialog. The final result should look like the dialog you saw at the beginning of the section Creating a Dialog GUI.

Integrating Windows and Dialogs in an Application

Up to this point, you’ve learned how to create a GUI for your main windows and dialogs with Qt Designer. In this section, you’ll learn how to integrate those GUIs into your Python code and build a real application. There are two main 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 first approach uses pyuic5, which is a tool included in the PyQt installation that allows you to translate 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 approach is suitable when you’re working with small GUIs that don’t involve substantial loading time.

Setting Up Windows and Dialogs for Use

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, then 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 Find and Replace dialog

Go ahead and create a new directory called sample_editor/. Inside this directory, create another directory called ui/ and copy 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 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
    │   └── help-content.png
    │
    ├── find_replace.ui
    └── main_window.ui

Since the main-window GUI is relatively complex, you can use pyuic5 to translate 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 below:

Now open a terminal and navigate to the sample_editor/ directory. Once you’re there, run the following command:

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 main window’s GUI. Here’s a small sample of the code:

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

Now your working directory should look 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
│   │   └── help-content.png
│   │
│   ├── find_replace.ui
│   └── main_window.ui
│
└── main_window_ui.py

Since your Find 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 as an argument and returns a QWidget subclass that implements the GUI.

This way of loading .ui files dynamically is rarely used in practice. You can use it with small dialogs that don’t require too much effort to load. With this approach, you don’t need to generate the Python code for the dialog’s GUI every time you modify the .ui file with Qt Designer, which can be a productivity and maintainability win in some cases.

Now that you’ve chosen a strategy for building each of your GUIs, it’s 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 can create the application and write the required code to use the main window and the Find and Replace dialog. Fire up your favorite code editor or IDE in your sample_editor/ directory and create a new file called app.py. Add the following code to it:

Here’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 way of loading the content of a .ui file dynamically.
  • Line 8 imports Ui_MainWindow, which contains the GUI for your main window.
  • Line 10 defines Window, which will provide your application’s main window. In this case, the class uses multiple inheritance. It inherits the main window functionality from QMainWindow and the GUI functionality from Ui_MainWindow.
  • Line 13 calls .setupUi(), which creates the whole GUI for your main 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 Replace dialog and execute it.
  • Line 25 defines .about(), which creates and launches a small dialog to provide information about the application. In this case, you use a built-in dialog based on QMessageBox.
  • Line 35 defines FindReplaceDialog, which provides the Find and Replace dialog.
  • Line 38 calls loadUi() to load the dialog’s GUI from the files ui/find_replace.ui.

Finally, on lines 41 to 44, you create the application, create and show the main window, and run the application’s main loop by calling .exec() on the application object.

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

If you want to use your own names instead of the names that Qt Designer generates, then you can go to the Property Editor and change the .objectName property to the name that seems right for you.

If you run this application, then you’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 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 you create applications in PyQt, you commonly build a main window and several dialogs. Building the GUI of those windows and dialogs can take a lot of time if you 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 can drag and drop all the required widgets onto an empty form, lay them out, and create your GUIs in almost no time. Those GUIs are saved in .ui files that you can translate into Python code and use in your applications.

In this tutorial, you 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 application’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 knowledge into action by using Qt Designer to create the GUIs of the windows and dialogs required to build a sample text editor application. You can get all the required code and resources to build this application by clicking the link below:

Эта статья предназначена для тех, кто только начинает своё знакомство с созданием приложений с графическим интерфейсом (GUI) на Python. В ней мы рассмотрим основы использования PyQt в связке с Qt Designer. Шаг за шагом мы создадим простое Python GUI приложение, которое будет отображать содержимое выбранной директории.

Что нам потребуется

Нам понадобятся PyQt и Qt Designer, ну и Python, само собой.

В этой статье используется PyQt5 с Python 3, но особых различий между PyQt и PySide или их версиями для Python 2 нет.

Windows: PyQt можно скачать здесь. В комплекте с ним идёт Qt Designer.

macOS: Вы можете установить PyQt с помощью Homebrew:

$ brew install pyqt5

Скачать пакет с большинством компонентов и инструментов Qt, который содержит Qt Designer, можно по этой ссылке.

Linux: Всё нужное, вероятно, есть в репозиториях вашего дистрибутива. Qt Designer можно установить из Центра Приложений, но PyQt придётся устанавливать через терминал. Установить всё, что нам понадобится, одной командой можно, например, так:

			# для Fedora:
$ sudo dnf install python3-qt5 qt-creator
# для Debian/Ubuntu:
$ sudo apt install python3-qt5 pyqt5-dev-tools qtcreator
		

После того как вы закончили с приготовлениями, откройте командную строку/терминал и убедитесь, что вы можете использовать команду pyuic5. Вы должны увидеть следующее:

			$ pyuic5
Error: one input ui-file must be specified
		

Если вы видите сообщение, что такой команды нет или что-то в таком роде, попробуйте загуглить решение проблемы для вашей операционной системы и версии PyQt.

Если вы используете Windows, то, скорее всего, путь C:\Python36\Scripts (измените 36 на вашу версию Python) не прописан в вашем PATH. Загляните в этот тред на Stack Overflow, чтобы узнать, как решить проблему.

Дизайн

Основы

Теперь, когда у нас всё готово к работе, давайте начнём с простого дизайна.

Откройте Qt Designer, где вы увидите диалог новой формы, выберите Main Window и нажмите Create.

Python GUI: создаём простое приложение с PyQt и Qt Designer 1

После этого у вас должна появиться форма — шаблон для окна, размер которого можно менять и куда можно вставлять объекты из окна виджетов и т.д. Ознакомьтесь с интерфейсом, он довольно простой.

Теперь давайте немного изменим размер нашего главного окна, т.к. нам не нужно, чтобы оно было таким большим. А ещё давайте уберём автоматически добавленное меню и строку состояния, поскольку в нашем приложении они не пригодятся.

Все элементы формы и их иерархия по умолчанию отображаются в правой части окна Qt Designer под названием Object Inspector. Вы с лёгкостью можете удалять объекты, кликая по ним правой кнопкой мыши в этом окне. Или же вы можете выбрать их в основной форме и нажать клавишу DEL на клавиатуре.

Python GUI: создаём простое приложение с PyQt и Qt Designer 2

В итоге мы имеем почти пустую форму. Единственный оставшийся объект — centralwidget, но он нам понадобится, поэтому с ним мы ничего не будем делать.

Теперь перетащите куда-нибудь в основную форму List Widget (не List View) и Push Button из Widget Box.

Макеты

Вместо использования фиксированных позиций и размеров элементов в приложении лучше использовать макеты. Фиксированные позиции и размеры у вас будут выглядеть хорошо (пока вы не измените размер окна), но вы никогда не можете быть уверены, что всё будет точно так же на других машинах и/или операционных системах.

Макеты представляют собой контейнеры для виджетов, которые будут удерживать их на определённой позиции относительно других элементов. Поэтому при изменении размера окна размер виджетов тоже будет меняться.

Давайте создадим нашу первую форму без использования макетов. Перетащите список и кнопку в форме и измените их размер, чтобы вышло вот так:

Python GUI: создаём простое приложение с PyQt и Qt Designer 3

Теперь в меню Qt Designer нажмите Form, затем выберите Preview и увидите что-то похожее на скриншот выше. Выглядит хорошо, не так ли? Но вот что случится, когда мы изменим размер окна:

Python GUI: создаём простое приложение с PyQt и Qt Designer 4

Наши объекты остались на тех же местах и сохранили свои размеры, несмотря на то что размер основного окна изменился и кнопку почти не видно. Вот поэтому в большинстве случаев стоит использовать макеты. Конечно, бывают случаи, когда вам, например, нужна фиксированная или минимальная/максимальная ширина объекта. Но вообще при разработке приложения лучше использовать макеты.

Основное окно уже поддерживает макеты, поэтому нам ничего не нужно добавлять в нашу форму. Просто кликните правой кнопкой мыши по Main Window в Object Inspector и выберите Lay outLay out vertically. Также вы можете кликнуть правой кнопкой по пустой области в форме и выбрать те же опции:

Python GUI: создаём простое приложение с PyQt и Qt Designer 5

Ваши элементы должны быть в том же порядке, что и до внесённых изменений, но если это не так, то просто перетащите их на нужное место.

Так как мы использовали вертикальное размещение, все элементы, которые мы добавим, будут располагаться вертикально. Можно комбинировать размещения для получения желаемого результата. Например, горизонтальное размещение двух кнопок в вертикальном будет выглядеть так:

Python GUI: создаём простое приложение с PyQt и Qt Designer 6

Если у вас не получается переместить элемент в главном окне, вы можете сделать это в окне Object Inspector.

Последние штрихи

Теперь, благодаря вертикальному размещению, наши элементы выровнены правильно. Единственное, что осталось сделать (но не обязательно), — изменить имя элементов и их текст.

В простом приложении вроде этого с одним лишь списком и кнопкой изменение имён не обязательно, так как им в любом случае просто пользоваться. Тем не менее правильное именование элементов — то, к чему стоит привыкать с самого начала.

Свойства элементов можно изменить в разделе Property Editor.

Подсказка: вы можете менять размер, передвигать или добавлять часто используемые элементы в интерфейс Qt Designer для ускорения рабочего процесса. Вы можете добавлять скрытые/закрытые части интерфейса через пункт меню View.

Нажмите на кнопку, которую вы добавили в форму. Теперь в Property Editor вы должны видеть все свойства этого элемента. В данный момент нас интересуют objectName и text в разделе QAbstractButton. Вы можете сворачивать разделы в Property Editor нажатием по названию раздела.

Измените значение objectName на btnBrowse и text на Выберите папку.

Должно получиться так:

Python GUI: создаём простое приложение с PyQt и Qt Designer 7

Именем объекта списка является listWidget, что вполне подходит в данном случае.

Сохраните дизайн как design.ui в папке проекта.

Превращаем дизайн в код

Конечно, можно использовать .ui-файлы напрямую из Python-кода, однако есть и другой путь, который может показаться легче. Можно конвертировать код .ui-файла в Python-файл, который мы потом сможем импортировать и использовать. Для этого мы используем команду pyuic5 из терминала/командной строки.

Чтобы конвертировать .ui-файл в Python-файл с названием design.py, используйте следующую команду:

			$ pyuic5 path/to/design.ui -o output/path/to/design.py
		

Пишем код

Теперь у нас есть файл design.py с нужной частью дизайна нашего приложения и мы начинать работу над созданием его логики.

Создайте файл main.py в папке, где находится design.py.

Используем дизайн

Для Python GUI приложения понадобятся следующие модули:

			import sys  # sys нужен для передачи argv в QApplication
from PyQt5 import QtWidgets
		

Также нам нужен код дизайна, который мы создали ранее, поэтому его мы тоже импортируем:

			import design  # Это наш конвертированный файл дизайна
		

Так как файл с дизайном будет полностью перезаписываться каждый раз при изменении дизайна, мы не будем изменять его. Вместо этого мы создадим новый класс ExampleApp, который объединим с кодом дизайна для использования всех его функций:

			class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self):
        # Это здесь нужно для доступа к переменным, методам
        # и т.д. в файле design.py
        super().__init__()
        self.setupUi(self)  # Это нужно для инициализации нашего дизайна
		

В этом классе мы будем взаимодействовать с элементами интерфейса, добавлять соединения и всё остальное, что нам потребуется. Но для начала нам нужно инициализировать класс при запуске кода. С этим мы разберёмся в функции main():

			def main():
    app = QtWidgets.QApplication(sys.argv)  # Новый экземпляр QApplication
    window = ExampleApp()  # Создаём объект класса ExampleApp
    window.show()  # Показываем окно
    app.exec_()  # и запускаем приложение
		

И чтобы выполнить эту функцию, мы воспользуемся привычной конструкцией:

			if __name__ == '__main__':  # Если мы запускаем файл напрямую, а не импортируем
    main()  # то запускаем функцию main()
		

В итоге main.py выглядит таким образом:

			import sys  # sys нужен для передачи argv в QApplication
from PyQt5 import QtWidgets
import design  # Это наш конвертированный файл дизайна

class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self):
        # Это здесь нужно для доступа к переменным, методам
        # и т.д. в файле design.py
        super().__init__()
        self.setupUi(self)  # Это нужно для инициализации нашего дизайна

def main():
    app = QtWidgets.QApplication(sys.argv)  # Новый экземпляр QApplication
    window = ExampleApp()  # Создаём объект класса ExampleApp
    window.show()  # Показываем окно
    app.exec_()  # и запускаем приложение

if __name__ == '__main__':  # Если мы запускаем файл напрямую, а не импортируем
    main()  # то запускаем функцию main()
		

Если запустить этот код: $ python3 main.py, то наше приложение запустится!

Python GUI: создаём простое приложение с PyQt и Qt Designer 8

Но нажатие на кнопку ничего не даёт, поэтому нам придётся с этим разобраться.

Добавляем функциональность в наше Python GUI приложение

Примечание Весь дальнейший код пишется внутри класса ExampleApp.

Начнём с кнопки Выберите папку. Привязать к функции событие вроде нажатия на кнопку можно следующим образом:

			self.btnBrowse.clicked.connect(self.browse_folder)
		

Добавьте эту строку в метод __init__ класса ExampleApp, чтобы выполнить привязку при запуске приложения. А теперь взглянем на неё поближе:

  • self.btnBrowse: здесь btnBrowse — имя объекта, который мы определили в Qt Designer. self говорит само за себя и означает принадлежность к текущему классу;
  • clicked — событие, которое мы хотим привязать. У разных элементов разные события, например, у виджетов списка есть itemSelectionChanged и т.д.;
  • connect() — метод, который привязывает событие к вызову переданной функции;
  • self.browse_folder — просто функция (метод), которую мы описали в классе ExampleApp.

Для открытия диалога выбора папки мы можем использовать встроенный метод QtWidgets.QFileDialog.getExistingDirectory:

			directory = QtWidgets.QFileDialog.getExistingDirectory(self, "Выберите папку")
		

Если пользователь выберет директорию, переменной directory присвоится абсолютный путь к выбранной директории, в противном случае она будет равна None. Чтобы не выполнять код дальше, если пользователь закроет диалог, мы используем команду if directory:.

Для отображения содержимого директории нам нужно импортировать os:

И получить список содержимого следующим образом:

Для добавления элементов в listWidget мы используем метод addItem(), а для удаления всех элементов у нас есть self.listWidget.clear().

В итоге функция browse_folder должна выглядеть так:

			def browse_folder(self):
    self.listWidget.clear()  # На случай, если в списке уже есть элементы
    directory = QtWidgets.QFileDialog.getExistingDirectory(self, "Выберите папку")
    # открыть диалог выбора директории и установить значение переменной
    # равной пути к выбранной директории

    if directory:  # не продолжать выполнение, если пользователь не выбрал директорию
        for file_name in os.listdir(directory):  # для каждого файла в директории
            self.listWidget.addItem(file_name)   # добавить файл в listWidget
		

Теперь, если запустить приложение, нажать на кнопку и выбрать директорию, мы увидим:

Python GUI: создаём простое приложение с PyQt и Qt Designer 9

Так выглядит весь код нашего Python GUI приложения:

			import sys  # sys нужен для передачи argv в QApplication
import os  # Отсюда нам понадобятся методы для отображения содержимого директорий

from PyQt5 import QtWidgets

import design  # Это наш конвертированный файл дизайна

class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self):
        # Это здесь нужно для доступа к переменным, методам
        # и т.д. в файле design.py
        super().__init__()
        self.setupUi(self)  # Это нужно для инициализации нашего дизайна
        self.btnBrowse.clicked.connect(self.browse_folder)  # Выполнить функцию browse_folder
                                                            # при нажатии кнопки

    def browse_folder(self):
        self.listWidget.clear()  # На случай, если в списке уже есть элементы
        directory = QtWidgets.QFileDialog.getExistingDirectory(self, "Выберите папку")
        # открыть диалог выбора директории и установить значение переменной
        # равной пути к выбранной директории

        if directory:  # не продолжать выполнение, если пользователь не выбрал директорию
            for file_name in os.listdir(directory):  # для каждого файла в директории
                self.listWidget.addItem(file_name)   # добавить файл в listWidget

def main():
    app = QtWidgets.QApplication(sys.argv)  # Новый экземпляр QApplication
    window = ExampleApp()  # Создаём объект класса ExampleApp
    window.show()  # Показываем окно
    app.exec_()  # и запускаем приложение

if __name__ == '__main__':  # Если мы запускаем файл напрямую, а не импортируем
    main()  # то запускаем функцию main()
		

Это были основы использования Qt Designer и PyQt для разработки Python GUI приложения. Теперь вы можете спокойно изменять дизайн приложения и использовать команду pyuic5 без страха потерять написанный код.

Summary: in this tutorial, you’ll learn how to use the Qt Designer tool to design user interfaces for PyQt applications.

PyQt6 tools are compatible with Python 3.9 at the time of writing this tutorial. Therefore, you need to install Python 3.9 to continue the tutorial.

Note that if you have Python 3.10 or higher, you can install Python 3.9 in a separate directory and use PyQt6 tools. For example, you can install Python 3.9 in the C:\Python39 directory on Windows.

Create a new virtual environment #

First, create a directory to host the PyQt6 projects e.g., D:\pyqt6

mkdir pyqt6Code language: Python (python)

Second, create a virtual environment using Python 3.9 using the venv module:

python -m venv D:\pyqt6\pyqt6-envCode language: Python (python)

Activate the virtual environment #

First, navigate to the pyqt6-env virtual environment directory:

cd D:\pyqt6\pyqt6-envCode language: Python (python)

Second, navigate to the Scripts folder:

cd ScriptsCode language: Python (python)

Third, activate the virtual environment by executing the activate.bat file:

activateCode language: Python (python)

It’ll show the following on Windows:

(pyqt6-env) d:\pyqt6\pyqt6-env\Scripts>Code language: Python (python)

Install PyQt6 and its tools #

First, execute the following command to install pyqt6 package in the pyqt6-env virtual environment:

pip install pyqt6Code language: Python (python)

Second, install the pyqt6-tools package that contains the Qt Designer and other related tools:

pip install pyqt6-toolsCode language: Python (python)

The pyqt-tools package will install the Qt Designer in the following location:

D:\pyqt6\pyqt6-env\Lib\site-packages\qt6_applications\Qt\bin\designer.exeCode language: Python (python)

Third, execute the pyuic6 command (within the pyqt6-env virtual environment) to check the version:

pyuic6 -VCode language: Python (python)

And you’ll see the following output:

6.1.0Code language: Python (python)

The pyuic6 is a tool for converting a design file (.ui) generated by Qt Designer to a Python file (.py).

Launch the Qt Designer #

From the Shell, type the designer command to launch the Qt Designer:

(pyqt6-env) d:\pyqt6\pyqt6-env\Scripts>designerCode language: Python (python)

The Qt Designer will look like this:

Qt Designer

Creating a login form #

We’ll create a simple login form using the Qt designer and load it into our Python program.

First, select File > New or press Ctrl-N keyboard shortcut to open the New Form dialog:

Qt Designer - New

Second, select the Widget from the templates\forms and click the Create button:

Qt Designer - Create a Widget

It’ll create a QWidget as follows:

Qt Designer - Form

You can set the layout for the widget, and drag and drop widgets from the Widget Box to the form.

Setting widget properties #

In the Property Editor, you can set a name for the widget e.g., login_form

Qt Designer - Widget Properties

and the window title:

Qt Designer -Window Title

Adding widgets to the login form #

First, add the widgets QLabel, QLineEdit, and QPushButton to the form:

Qt Designer - widgets

The following table lists the fields, their types, and names:

Field Widget Object Name
Login Window QWidget login_form
Email Address QLineEdit email_line_edit
Password QLineEdit password_line_edit
Login Button QPushButton btn_login

Second, set the echo mode of the password field to Password:

Qt Designer - Password field

Third, right-click the widget and set its layout to Form Layout:

Qt Designer - Set Form Layout

The form will change to the following:

Qt Designer - Form Layout

Fourth, change the size of the Login button by setting its Horizontal Size Policy to Fixed:

Qt Designer - Change the button size

Fifth, save the form to the D:\pyqt6 directory as login_form.ui file.

Sixth, select Form > Preview... menu or the keyboard shortcut Ctrl-R to preview the form:

Qt Designer - Preview

Finally, close the Qt Designer.

There’re two ways to use the login_form.ui from a Python program:

  1. Convert the .ui file to Python code and use the generated code from the program.
  2. Directly use the .ui file in the program.

Converting .ui file to Python code #

First, execute the following command to convert the login_form.ui file to login_form.py file:

pyuic6 -o login_form.py login_form.uiCode language: Python (python)

Note that you need to run the pyuic6 from the pyqt6-env virtual environment.

The pyuic6 generated the login_form.py from the login_form.ui file. The login_form.py contains the following generated Python code:

# Form implementation generated from reading ui file 'login_form.ui'
#
# Created by: PyQt6 UI code generator 6.1.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt6 import QtCore, QtGui, QtWidgets


class Ui_login_form(object):
    def setupUi(self, login_form):
        login_form.setObjectName("login_form")
        login_form.resize(269, 108)
        self.formLayout = QtWidgets.QFormLayout(login_form)
        self.formLayout.setObjectName("formLayout")
        self.label = QtWidgets.QLabel(login_form)
        self.label.setObjectName("label")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label)
        self.email_line_edit = QtWidgets.QLineEdit(login_form)
        self.email_line_edit.setObjectName("email_line_edit")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.ItemRole.FieldRole, self.email_line_edit)
        self.label_2 = QtWidgets.QLabel(login_form)
        self.label_2.setObjectName("label_2")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_2)
        self.password_line_edit = QtWidgets.QLineEdit(login_form)
        self.password_line_edit.setEchoMode(QtWidgets.QLineEdit.EchoMode.Password)
        self.password_line_edit.setObjectName("password_line_edit")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.ItemRole.FieldRole, self.password_line_edit)
        self.btn_login = QtWidgets.QPushButton(login_form)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Fixed, QtWidgets.QSizePolicy.Policy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btn_login.sizePolicy().hasHeightForWidth())
        self.btn_login.setSizePolicy(sizePolicy)
        self.btn_login.setObjectName("btn_login")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.ItemRole.FieldRole, self.btn_login)

        self.retranslateUi(login_form)
        QtCore.QMetaObject.connectSlotsByName(login_form)

    def retranslateUi(self, login_form):
        _translate = QtCore.QCoreApplication.translate
        login_form.setWindowTitle(_translate("login_form", "Login"))
        self.label.setText(_translate("login_form", "Email Address"))
        self.label_2.setText(_translate("login_form", "Password"))
        self.btn_login.setText(_translate("login_form", "Login"))Code language: Python (python)

It’s important to note that you should never manually change the login_form.py file. Because all your manual adjustments will be lost if you edit the login_form.ui in the Qt Designer and regenerate the login_form.py again.

Second, create the login.py file and import the login_ui.py file:

import sys
from PyQt6.QtWidgets import QApplication, QWidget
from login_form import Ui_login_form


class Login(QWidget):
    def __init__(self):
        super().__init__()

        # use the Ui_login_form
        self.ui = Ui_login_form()       
        self.ui.setupUi(self)       
        
        # show the login window
        self.show()
    

if __name__ == '__main__':
    app = QApplication(sys.argv)
    login_window = Login()
    sys.exit(app.exec())Code language: Python (python)

How it works.

  1. Import Ui_login_form class from the login_form.py file
  2. Create a new instance of the Ui_login_form and call the setupUi() method to set up the user interfaces.

Third, execute the login.py file:

python login.pyCode language: Python (python)

It’ll show the login window:

Qt Designer - Login Window

Referencing child widgets #

To use the child widgets of Ui_login_form widget, you reference their names using the self.ui variable.

For example, you can add a simple authentication when the user enters an email address and password and click the Login button as follows:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QMessageBox
from login_form import Ui_login_form


class Login(QWidget):
    def __init__(self):
        super().__init__()

        # use the Ui_login_form
        self.ui = Ui_login_form()       
        self.ui.setupUi(self)       

        # authenticate when the login button is clicked
        self.ui.btn_login.clicked.connect(self.authenticate)
        
        # show the login window
        self.show()

    def authenticate(self):
        email = self.ui.email_line_edit.text()
        password = self.ui.password_line_edit.text()

        if email == '[email protected]' and password == '123456':
            QMessageBox.information(self, 'Success',"You're logged in!")
        else:
            QMessageBox.critical(self, 'Error',"Invalid email or password.")
    

if __name__ == '__main__':
    app = QApplication(sys.argv)
    login_window = Login()
    sys.exit(app.exec())Code language: Python (python)

How it works.

First, connect the clicked signal of the button to the authenticate method. Notice that we reference the btn_login button via the self.ui variable:

self.ui.btn_login.clicked.connect(self.authenticate)Code language: Python (python)

Second, define the authenticate() method that gets values from the email_line_edit and password_line_edit and perform a simple check of these values against hard-coded values:

def authenticate(self):
    email = self.ui.email_line_edit.text()
    password = self.ui.password_line_edit.text()

    if email == '[email protected]' and password == '123456':
        QMessageBox.information(self, 'Success',"You're logged in!")
    else:
        QMessageBox.critical(self, 'Error',"Invalid email or password.")Code language: Python (python)

Security Notice: Never do this in real applications.

Besides creating an instance of the Ui_login_form inside the login window, you can inherit the Ui_login_form window using multiple inheritances and directly reference the child widgets like this:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QMessageBox
from login_form import Ui_login_form


class Login(QWidget,Ui_login_form):
    def __init__(self):
        super().__init__()

        # setup the UI
        self.setupUi(self)       

        # authenticate when the login button is clicked
        self.btn_login.clicked.connect(self.authenticate)
        
        # show the login window
        self.show()

    def authenticate(self):
        email = self.email_line_edit.text()
        password = self.password_line_edit.text()

        if email == '[email protected]' and password == '123456':
            QMessageBox.information(self, 'Success',"You're logged in!")
        else:
            QMessageBox.critical(self, 'Error',"Invalid email or password.")
    

if __name__ == '__main__':
    app = QApplication(sys.argv)
    login_window = Login()
    sys.exit(app.exec())Code language: Python (python)

Using .ui file directly #

Another way to use the design generated by the Qt Designer is to load the .ui file directly using the loadUi() function of the uic module:

from PyQt6.QtWidgets import QApplication, QWidget, QMessageBox
from PyQt6 import uic
import sys

class Login(QWidget):
    def __init__(self):
        super().__init__()
        self.ui = uic.loadUi('login_form.ui', self)

        # authenticate when the login button is clicked
        self.ui.btn_login.clicked.connect(self.authenticate)

        self.show()
    
    def authenticate(self):
        email = self.email_line_edit.text()
        password = self.password_line_edit.text()

        if email == '[email protected]' and password == '123456':
            QMessageBox.information(self, 'Success',"You're logged in!")
        else:
            QMessageBox.critical(self, 'Error',"Invalid email or password.")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    login_window = Login()
    sys.exit(app.exec())Code language: Python (python)

The loadUi() function returns an instance of the QWidget and you can reference the child widgets via the self.ui variable.

When you should use Qt Designer #

The .ui file generated by the Qt designer creates an abstraction layer between the available widget and the code that consumes it.

Therefore, if you are starting out with PyQt, you should code the UI manually instead of using Qt Designer. By doing this, you know exactly what widgets are available in the application.

However, if you’re familiar with PyQt and work on a large application, you should use Qt Designer to create a good design and improve productivity.

Summary #

  • Use Qt Designer to design user interfaces for large applications.
  • Use the pyuic6 tool to convert a .ui file into a Python source code file.
  • Use loadUi() function of the uic module to load the .ui file directly.

Was this tutorial helpful ?


In this article, we will first discuss how to install the desktop UI designer application known as Qt Designer from Qt Software. We will install Qt Designer as a system-wide independent application on both Windows 10 and Ubuntu 24.04. Next, we will briefly discuss using Qt Designer to make a simple dialog with two buttons.


In the third step, we install the Python PyQt software version 6, the PyQt6 library. Still in this third step, we are using a utility that comes with PyQt6 to convert the dialog we made in the second step into Python code. In the fourth step, we write a simple Python script which subclasses the generated dialog in the previous step, adds some code to the subclass, and displays the dialog. Finally, we discuss some background information.

Install Qt Designer as a System-Wide Independent Application

Please note that independent means not depending on the
pyqt6-tools library
as described in a later section.

On Ubuntu 24.04

The instructions in this section are based on the
How to install PyQt 6 Designer in Ubuntu 24.10
post. Run the following commands to install:

$ sudo apt install qt6-base-dev
$ sudo apt install qt6-tools-dev

The location of the executable is /usr/lib/qt6/bin/designer.
We can verify with the following command:

behai@HP-Pavilion-15:~$ ls -l /usr/lib/qt6/bin/designer

For my installation, the output is:

-rwxr-xr-x 1 root root 564576 Apr 16  2024 /usr/lib/qt6/bin/designer

To create an entry for Qt Designer in the Application area, we need to create the
/home/behai/.local/share/application/desginer.desktop file.
Replace behai with your own user name.

Content of /home/behai/.local/share/application/desginer.desktop:
[Desktop Entry]
Version=1.0
Name=Qt Designer 6
Comment=Qt Designer 6
Exec=/usr/lib/qt6/bin/designer
Icon=/home/behai/.local/share/applications/qt.ico
Terminal=false
Type=Application
Categories=Utility;Application;

The icon located at /home/behai/.local/share/applications/qt.ico is sourced from
qt.ico.
Finally, set the required permissions for designer.desktop:

$ chmod 755 designer.desktop

💥 I have found that I have to reboot to get the icon to display. Please see the screenshot below:

On Windows 10

It is fairly simple. Download the installation file Qt Designer Setup.exe
from Qt Designer Download, it is only
40MB. After a successful installation, Qt Designer should appear in the Start Menu as shown in the screenshot below:

Qt Designer Usage

On Windows 10

On starting, Qt Designer greets us with the New Form – Qt Designer window,
where we can choose what we want to create. Select the first entry,
Dialog with Buttons Bottom. Then, on the right-hand side, under the last entry
Display Widgets, drag and drop a Label onto the dialog.
Use the QWidget Property Editor on the right-hand side to change the label to something, as shown in the screenshot below:

I saved this dialog to F:\pydev\designer_ui\learn_dlg.ui. It is in
XML format.

On Ubuntu 24.04

I don’t want to start from the beginning, so I just copied
F:\pydev\designer_ui\learn_dlg.ui from Windows 10 to
the corresponding directory on Ubuntu 24.04: ~/pydev/designer_ui/learn_dlg.ui.
Double-click on the Qt Designer icon in the Application area, as
previously discussed,
then open ~/pydev/designer_ui/learn_dlg.ui:

It looks better than the Windows 10 one; the buttons have icons like the classic Borland Delphi form designer.
To get finer positional placements and sizes, under the
QWidget Property Editor on the right-hand side, look for
geometry. We can use the keyboard to punch in the coordinates and sizes for each widget, allowing for finer adjustments by directly entering the numbers rather than using the mouse to drag them around.

The
PyQt6
Library Installation and Usage

The active virtual environment is F:\pydev\venv on Windows 10
and /home/behai/pydev/venv on Ubuntu 24.04. Install PyQt6
using the following command:

▶️Windows 10: .\venv\Scripts\pip.exe install PyQt6
▶️Ubuntu 24.04: ./venv/bin/pip install PyQt6

The following discussion is based on this discussion. 👉 Please note that the sub-directory pydev/py_ui/ must be created first.

On Ubuntu 24.04

To convert /behai/home/pydev/designer_ui/learn_dlg.ui to
/behai/home/pydev/py_ui/learn_dlg.py, either of the below commands will work:

$ ./venv/bin/pyuic6 -o ./py_ui/learn_dlg.py -x ./designer_ui/learn_dlg.ui
$ ./venv/bin/python -m PyQt6.uic.pyuic -o ./py_ui/learn_dlg.py -x ./designer_ui/learn_dlg.ui

💥 As /home/behai/pydev/py_ui/learn_dlg.py is a generated module, the next time the conversion takes place, it gets overwritten. In our code, we must subclass it rather than adding code directly to it.

On Windows 10

The commands are similar:

.\venv\Scripts\pyuic6.exe -o .\py_ui\learn_dlg.py -x .\designer_ui\learn_dlg.ui
.\venv\Scripts\python.exe -m PyQt6.uic.pyuic -o .\py_ui\learn_dlg.py -x .\designer_ui\learn_dlg.ui

The generated module ./py_ui/learn_dlg.py is fairly straightforward. Most of the code is about preparing the UI widgets, and it assumes that the methods for the buttons’ click events exist.


PyQt6
Example: Subclassing ./pydev/py_ui/learn_dlg.py's Class Ui_Dialog

The script below implements the click-events for each button. To shut down the script, users need to click on the dialog’s Close button.

import sys

from PyQt6.QtWidgets import QMainWindow

from py_ui.learn_dlg import *

class LearnPyQtWindow(QMainWindow, Ui_Dialog):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowFlags(QtCore.Qt.WindowType.CustomizeWindowHint | 
                            QtCore.Qt.WindowType.WindowCloseButtonHint )
        self.show()

    def accept(self):
    
    print("You clicked the OK button...")
        # Enable self.close() to close the dialog on clicking.
        # self.close()

    def reject(self):
        print("You clicked the Cancel button...")
        # Enable self.close() to close the dialog on clicking.
        # self.close()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    login = LearnPyQtWindow()
    sys.exit(app.exec())

Let’s briefly explain the script:

● Turning off the dialog’s Maximize and Minimize buttons:

        self.setWindowFlags(QtCore.Qt.WindowType.CustomizeWindowHint | 
                            QtCore.Qt.WindowType.WindowCloseButtonHint )

This line actually means only the dialog’s Close button is shown.

● The accept and reject methods:
These are the buttons’ click-event methods that the generated module
./pydev/py_ui/learn_dlg.py assumes are implemented. See lines 33 and 34:

        self.buttonBox.accepted.connect(Dialog.accept) # type: ignore
        self.buttonBox.rejected.connect(Dialog.reject) # type: ignore

On Windows 10, the script shows:

We can see that only the Close button is visible and functional. The dialog is shown in the center of the screen; I did not set this position in the design—it is its default behavior.

On Ubuntu 24.04, the script shows:

The Maximize and Minimize buttons are visible but disabled. The Close button is functional. 💥 The dialog is not centered on the screen as it is on Windows 10.

The
pyqt6-tools Library,
Released: Mar 28, 2023

On Windows 10, I first installed Qt Designer with the pyqt6-tools library,
but only with Python version 3.11.9; versions
3.12.xx and 3.13.xx fail to install
pyqt6-tools. In a virtual environment venv,
the Qt Designer executable location is
.\venv\Lib\site-packages\qt6_applications\Qt\bin\designer.exe.

On Ubuntu 24.04, Python 3.11.xx is no longer available.
I have version 3.13.0 installed. Installing pyqt6-tools
using Python 3.13.0 results in other errors as well. Please see the screenshot below:

Trying to solve these problems has led me to the realization that the Qt Designer application can be installed as an independent application, as discussed. This should make sense too, as we do not need this application on a per-virtual-environment basis.

❻ While trying to sort out the problems with installing Qt Designer, I came across
The Qt Group
website, where they offer a Qt Installer application for download.
The installer itself is about 50 MB. When I ran it, the default installation requires 300 GB (three hundred gigabytes).
I attempted to turn off most options, leaving only what I assumed would install the Qt Designer application, but it still required around 40 GB—so I abandoned it altogether.

❼ Other related sites that I find helpful:

  1. PyQt5 Tutorial
    — I started off learning
    PyQt
    with this site. I completed all the tutorials, and then I found out that
    PyQt6
    is the latest version.
  2. PythonGUIs
    — I have found some useful information on
    PyQt6
    from this site.

❽ Having successfully gathered the information to install the Qt Designer application on both operating systems is satisfying. The information is readily available on the internet, but strangely enough, not centralized. I still have not figured out the actual official home page for the Qt Designer application yet 😂… I assume it is the Qt Group website.

Thank you for reading. I hope you find the information in this post useful. Stay safe, as always.

✿✿✿

Feature image sources:

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Запуск windows 2012 в безопасном режиме
  • 2 gis для windows
  • Git bash add ssh key windows
  • Как установить windows server 2003 на компьютер
  • Сервер тонких клиентов на windows server