PyQt5 - Lesson 002. Hello World on PyQt5

qt, PyCharm, qt уроки, qt5, PyQt5

Python - a high-level general purpose programming language, focused on improving developer productivity and code readability. And also widely used for writing Web-based applications. But to work with Qt for Python was developed Library PyQt5 by Riverbank Computing, which is a set of "anchors" to Qt5 library.

Out of interest, I decided to write a small Hello World using PyQt5.


First install Python, in my case it is Python 3.5.2.

For Windows, you can download the installation package from the official Python website. For Linux, we can use the standard package manager.

Next, you need to install PyQt5. In the case of Linux can be installed using either a standard package manager. For example, for deb-based distributions:

sudo apt-get install python python3-pyqt5 pyqt5-dev-tools

Either install the first pip utility to install Python packages:

sudo apt-get install python-pip

And to install with the help of this tool, which will be similar for Windows, and for Linux systems:

pip install PyQt5

IDE PyCharm has been chosen to develop in Python.

Hello World

Now write a small program to PyQt5, which will run the application window with the words and have one menu item in the menu bar. By clicking on the item will close the application.

Full text of program

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, qApp, QAction
from PyQt5.QtCore import QSize

# Inherit from QMainWindow
class MainWindow(QMainWindow):
    # override the class constructor
    def __init__(self):
        # Invoke the method of super class

        self.setMinimumSize(QSize(480, 320))    # Set sizes
        self.setWindowTitle("Hello world!!!")   # Set title of window
        central_widget = QWidget(self)          # Create a central widget
        self.setCentralWidget(central_widget)   # Set the central widget

        grid_layout = QGridLayout(self)         # Create a QGridLayout
        central_widget.setLayout(grid_layout)   # Set Layout to central widget

        title = QLabel("Hello World on the PyQt5", self)    # Create a label
        title.setAlignment(QtCore.Qt.AlignCenter)   # Set alignment of text
        grid_layout.addWidget(title, 0, 0)          # and add it to layout

        exit_action = QAction("&Exit", self)    
        # Connect the signal triggered in the slot quit qApp. 
        # Signals and Slots syntax PyQt5 is markedly different from the one used Qt5 C ++
        # Set in the menu bar Action.
        file_menu = self.menuBar()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    mw = MainWindow()


1. if __name__ == "__main__":

In a Python applications can often find the following construction:

if __name__ == "__main__":

Since you can specify the Python-script, a program code using this design to perform in the event that it runs as a standalone application. In case, if the script will be imported into another script, the code that will follow this structure will not be called.

2. Syntax of signals and slots

In PyQt5 use the following syntax signals and slots as shown in the example QAction use.

exit_action = QAction("&Exit", self)    # Создаём Action с помощью которого будем выходить из приложения

While in Qt C ++ the same thing would look like this:

QAction *exit = new QAction("&Exit", this);
connect(exit, &QAction::triggered, qApp, &QApplication::quit);

3. Python

Perhaps the most obvious;-)
Here without comment.


The result is a program similar to the following.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

Feb. 17, 2020, 1:41 p.m.

C++ - Тест 003. Условия и циклы

  • Result:85points,
  • Rating points6
Feb. 17, 2020, 5:02 a.m.

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Feb. 17, 2020, 4:49 a.m.

C++ - Test 001. The first program and data types

  • Result:80points,
  • Rating points4
Last comments
Feb. 17, 2020, 2:22 a.m.
Evgenij Legotskoj

Добрый день. Это кастомный тег, помещается в файл, который находится в каталоге templatetags myapp/ templatetags/
Feb. 16, 2020, 12:36 p.m.

Добрый вечер! Монжно по подробней о теге get_companion? ссылка не работает.
Feb. 16, 2020, 8:35 a.m.
Evgenij Legotskoj

Добрый день. На GitHub исходники, можете посмотреть в официальном репозитории
Feb. 16, 2020, 8:29 a.m.

Здравстсвуйте Евгений, непонятно мне где эти исходники найти?
Now discuss on the forum
Feb. 18, 2020, 2:16 p.m.

Нет, стоит minLevel=1 А что это значит? Поменял на 0, но ничего не изменилось. Файл настроек выглядит так [listener]; host=…
Feb. 18, 2020, 6:19 a.m.

Привет , кто -нибудь подскажет как реализовать перетаскивание обьектов из листвью , и как это вообще делается ? Суть в том ,чтобы при объекта из листвью модели ,знать что за обьект. В…
Feb. 17, 2020, 2:11 p.m.

Добрый день. Сейчас инициализация моего приложение выглядит приблизительно так: sys_argv = sys.argvsys_argv += ['--style', 'material']app = QGuiApplication(sys_argv)app.setWindowIcon…
Feb. 16, 2020, 1:13 p.m.

Всем привет. есть те кто сталкивался с данной прогой? Нужна наводка просто как правильно из кучи инфы что содержит файл trace.dat и скармливается kernelshark вытащить причину долгого с…
Feb. 16, 2020, 10:35 a.m.
Igor' Poroshin

#include <QSqlError>#include <QSqlQuery>...if (!model->select()) { qDebug() << model->lastError().text(); qDebug() << model->query().lastQue…
© EVILEG 2015-2019
Recommend hosting TIMEWEB