Development of Desktop applications in Python and PySide6/PyQt6 libraries. Part 1. Installation and first application on PySide6

Today we will look at the excellent PySide6 library, which is a wrapper for interacting with Qt using the Python language, which allows you to use Python to write Qt desktop applications. Of course, it is worth considering that Python is not the best solution for implementing Desktop applications. In this guide, you will already need minimal knowledge of Python and OOP.

Python for Qt logo

Python for Qt logo

To implement the code we need:

  • Any development environment or IDE convenient for you (I use PyCharm);

  • Python version 3.7+ (My current version is 3.11);

  • Python for Qt Documentation

Creating and activating a virtual environment

A virtual environment in Python is an isolated space in which you can manage dependencies and versions of Python packages for a specific project. It allows you to isolate a project from other projects on your computer to avoid conflicts between package versions and ensure project portability.

To create a virtual environment, run the following command in the console:

python -m venv venv

After activating the virtual environment in your project, run:

If you are using Windows:

.\venv\Scripts\activate.bat

If you use Linux/MacOs:

source venv/bin/activate

Installing PySide6

I will be installing PySide6 using the pip package manager built into Python. Next, in your terminal or console, run the following command:

If you are using Windows:

pip install pyside6

If you use Linux/MacOS:

pip3 install pyside6

After successful installation, you can start writing code. But first I would like to tell you about the built-in modules of PySide6

Verifying PySide6 Installation

Next, if you have successfully installed PySide6, we can check the current version.

import PySide6
print(PySide6.__version__)
Output current version of PySide6

Output current version of PySide6

:Main modules in PySide6

PySide6 includes a large number of modules, combined into the PySide6 package. Next, let's look at some of the most important ones:

  1. PySide6.QtCore: This module provides core classes and functions for working with events, times, strings, lists, and other basic data types. It also includes classes for working with streams, files, signals and slots (you'll learn about signals and slots in later parts), making it one of the most important modules in PySide6.

  2. PySide6.QtWidgets: This module provides classes for creating user interfaces such as windows, buttons, text fields, tables, menus and dialog boxes. With it, you can create and manage various UI elements of your application.

  3. PySide6.QtGui: This module contains classes for working with graphical elements such as drawing, fonts, cursors, images and icons. It also provides classes for working with input events such as mouse and keyboard.

  4. PySide6.QtNetwork: This module provides classes for working with the network, such as TCP and UDP sockets, HTTP requests and responses, and SSL connections.

  5. PySide6.QtSql: This module provides classes for working with databases using SQL. It includes support for various databases such as SQLite, MySQL and PostgreSQL.

  6. PySide6.QtPrintSupport: This module provides classes for printing documents and managing print settings.

This is just a small overview of the most important modules in PySide6. Each of these modules provides a rich set of classes and functions for developing different types of GUI applications in Python.

Utilities that come out of the box in PySide6

Once you have installed PySide6, there are utilities available out of the box that help you develop applications using PySide6. Here they are:

  1. pyside6-uic: A utility for converting .ui files (created in Qt Designer) into corresponding Python code that creates widgets and windows using PySide6.

  2. pyside6-rcc: A utility for converting .qrc files (resource files) into Python modules that can be used to access embedded resources such as images, fonts and styles.

  3. pyside6-lupdate: A utility for updating .ts files (translation files) according to the application source code containing the strings to be translated.

  4. pyside6-lrelease: A utility for compiling .ts files into .qm files (compiled translation files), which can then be loaded by PySide6 applications for localization.

  5. pyside6-cm: A utility for converting .qm files (compiled translation files) into Python modules that can be used to access localized strings.

  6. pyside6-designer is a graphical interface editor similar to Qt Designer that comes with PySide6. This utility provides a convenient way to create and edit user interfaces for your applications.

This is only a part of the basic utilities, but the most frequently used in development. Don’t be alarmed for now, as soon as you start using them in practice, everything will fall into place in your head – where and how to use them.

Making our first “Hello World” application

Let's get to practice. As is customary for all novice programmers, the first thing we do is implement a program that displays the text “Hello World”. Now we will make the first interface with you.

from PySide6 import QtWidgets  # Импорт модуля QtWidgets из библиотеки PySide6
import sys  # Импорт модуля sys для работы с системными параметрами и выходом из программы

# Создание экземпляра QApplication, который управляет основным циклом событий и инициализацией приложения
app = QtWidgets.QApplication(sys.argv)

# Создание главного окна приложения
window = QtWidgets.QWidget()

# Установка заголовка главного окна
window.setWindowTitle("PySide6 Application")

# Установка размеров главного окна
window.resize(300, 250)

# Создание метки (надписи) с текстом "Hello World!"
lbl = QtWidgets.QLabel("Hello World!")

# Создание кнопки с надписью "Close"
btn = QtWidgets.QPushButton("Close")

# Создание вертикального блока для размещения метки и кнопки
# Вертикальный блок из себя представляет контейнер в который мы помещаем элементы
box = QtWidgets.QVBoxLayout()

# Добавление метки и кнопки в вертикальный блок
box.addWidget(lbl)
box.addWidget(btn)

# Установка вертикального блока в качестве компоновщика главного окна
window.setLayout(box)

# Подключение обработчика события "clicked" кнопки к методу app.quit, вызывающему завершение приложения
btn.clicked.connect(app.quit)

# Отображение главного окна
window.show()

# Запуск основного цикла обработки событий приложения
sys.exit(app.exec())  # После завершения цикла приложение выходит из программы

If you run this code, you will get your application window with the text “Hello World” and a “Close” button

Application window

Application window

In the next part of the guide, we will look at Widgets and their layout, and also touch on the topic of signals and slots and Qt Designer.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *