Pyqt5 [GUI-Designing]

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.

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:

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

Here, you create a Python virtual environment, activate it, and install pyqt5 and pyqt5-toolspyqt5 installs PyQt and a copy of the required Qt libraries, while pyqt5-tools installs a set of Qt tools that includes Qt Designer.

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:


The window in the foreground is Qt Designer’s New Form dialog. The window in the background is Qt Designer’s main window

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:

TemplateForm TypeWidgetsBase Class
Dialog with Buttons BottomDialogOK and Cancel buttons laid out horizontally on the bottom-right cornerQDialog
Dialog with Buttons RightDialogOK and Cancel buttons laid out vertically on the top-right cornerQDialog
Dialog without ButtonsDialogNoQDialog
Main WindowMain WindowA menu bar at the top and a status bar at the bottomQMainWindow
Widget
WidgetNoQWidget

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.

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.

  • Dialog with Buttons bottom



  • Dialog with Buttons Right



  • Main Window

 

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 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




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.

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.











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:

Dialog ClassPurpose
QFontDialogSelecting and setting a font of a given text
QPrintDialogSpecifying the settings of a printer
QProgressDialogShowing the progress of a long-running operation
QColorDialogSelecting and setting colors
QInputDialogGetting a single value from the user
QFileDialogSelecting files and directories
QMessageBoxDisplaying messages such as errors, general information, warnings, and questions
QErrorMessageDisplaying error message

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.

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:

ModePurposeMenu OptionKeyboard Shortcut
Edit WidgetsEditing widgetsEdit → Edit WidgetsF3
Edit Signals/SlotsConnecting built-in signals and slotsEdit → Edit Signals/SlotsF4
Edit BuddiesSetting up keyboard acceleratorsEdit → Edit BuddiesNo
Edit Tab OrderSetting up the tab order of widgetsEdit → Edit Tab OrderNo

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.

Creating Your First PyQt Application

Now that you have a working PyQt installation, you’re ready to start coding. You’re going to create a “Hello, World!” application with Python and PyQt. Here are the steps you’ll follow:

  1. Import QApplication and all the required widgets from PyQt5.QtWidgets.
  2. Create an instance of QApplication.
  3. Create an instance of your application’s GUI.
  4. Show your application’s GUI.
  5. Run your application’s event loop (or main loop).
# Filename: hello.py

"""Simple Hello World example with PyQt5."""

import sys

# 1. Import `QApplication` and all the required widgets
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QWidget
# 2. Create an instance of QApplication
app = QApplication(sys.argv)
# 3. Create an instance of your application's GUI
window = QWidget()
window.setWindowTitle('PyQt5 App')
window.setGeometry(100, 100, 280, 80)
window.move(60, 15)
helloMsg = QLabel('<h1>Hello World!</h1>', parent=window)
helloMsg.move(60, 15)
# 4. Show your application's GUI
window.show()

# 5. Run your application's event loop (or main loop)
sys.exit(app.exec_())




"""Horizontal layout example."""

import sys

from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QWidget

app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle('QHBoxLayout')
layout = QHBoxLayout()
layout.addWidget(QPushButton('Left'))
layout.addWidget(QPushButton('Center'))
layout.addWidget(QPushButton('Right'))
window.setLayout(layout)
window.show()
sys.exit(app.exec_())




"""Form layout example."""

import sys

from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QFormLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QWidget

app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle('QFormLayout')
layout = QFormLayout()
layout.addRow('Name:', QLineEdit())
layout.addRow('Age:', QLineEdit())
layout.addRow('Job:', QLineEdit())
layout.addRow('Hobbies:', QLineEdit())
window.setLayout(layout)
window.show()
sys.exit(app.exec_())



 #Filename: main_window.py

"""Main Window-Style application."""

import sys

from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QStatusBar
from PyQt5.QtWidgets import QToolBar

class Window(QMainWindow):
    """Main Window."""
    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)
        self.setWindowTitle('QMainWindow')
        self.setCentralWidget(QLabel("I'm the Central Widget"))
        self._createMenu()
        self._createToolBar()
        self._createStatusBar()

    def _createMenu(self):
        self.menu = self.menuBar().addMenu("&Menu")
        self.menu.addAction('&Exit', self.close)

    def _createToolBar(self):
        tools = QToolBar()
        self.addToolBar(tools)
        tools.addAction('Exit', self.close)

    def _createStatusBar(self):
        status = QStatusBar()
        status.showMessage("I'm the Status Bar")
        self.setStatusBar(status)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())


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. 

BY
20cs045(ANUJ PATEL)
20cs051(HARSHIV PATEL)



























Comments