Hello World with PyQt and Python

Are you looking for a way to create native apps with your favourite language Python? Qt5 is a widget framework with bindings for popular language like Rust, Javascript and Python. After reading this, you know how to setup a project that shows a native window with a label in under five minutes!

In this tutorial you will learn how to use PyQt5 to create a hello world with Qt5 and Python. The example creates an application with a window containing one label. The structure looks like this:

structure of pyqt5 app

Create project and install PyQt

This example is written on MacOS but should work on Windows and Linux. Start by opening a terminal and create a project:

mkdir helloworld
cd helloworld

Create a virtual environment and install PyQt5 in it:

python3 -m venv env
source env/bin/activate
pip install pyqt5

Create file main.py and enter:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

app = QApplication(sys.argv)
window = QMainWindow()
window.setWindowTitle("Hello World")
label = QLabel('I must have left my house at 8, because I always do.')
label.setMargin(20)
window.setCentralWidget(label)
window.show()
app.exec_()

Start the app in the Terminal with:

python3 main.py

The result should look like this.

hello world with pyqt5

Written by Loek van den Ouweland on February 11, 2019. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.