Evgenii Legotckoi
Evgenii LegotckoiSept. 3, 2016, 11:03 a.m.

PyQt5 - Lesson 002. Hello World on 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.

Installing

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
        QMainWindow.__init__(self)

        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)    
        exit_action.setShortcut('Ctrl+Q')       
        # Connect the signal triggered in the slot quit qApp. 
        # Signals and Slots syntax PyQt5 is markedly different from the one used Qt5 C ++
        exit_action.triggered.connect(qApp.quit)
        # Set in the menu bar Action.
        file_menu = self.menuBar()
        file_menu.addAction(exit_action)


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

Differences

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.

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 с помощью которого будем выходить из приложения
exit_action.triggered.connect(qApp.quit)

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

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

Python

Perhaps the most obvious;-)
Here without comment.

Conclusion

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.

Do you like it? Share on social networks!

ИР
  • May 13, 2020, 2:58 a.m.

Отлично получилось. Работает. Спс

ВР
  • Aug. 17, 2021, 7:09 p.m.

ImportError: cannot import name 'QtCore' from 'PyQt5' (unknown location)

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 6:56 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 6:45 p.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 6:35 p.m.

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

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 9:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 26, 2023, 1:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 11:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 12:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 7:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 9:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 8:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 4:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 6:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks