Make a graphical interface with PyQt?

A PyQt program always has the same three steps: create the application object, create your window, show the window. Once you know these three lines you can add any widget you like.

Graphical interfaces made with PyQt run on: Microsoft Windows, Apple Mac OS X and Linux. We will create a Hello World app with PyQt.

PyQt installation

PyQt is available for both Python 2 (2.7.9 tested) and Python 3.

To install write:

pip3 install pyqt5

With apt-get you can use: python3-pyqt5

PyQt hello world

The app we write will show the message “Hello World” in a graphical window. Import the PyQt5 module.

# https://pythonprogramminglanguage.com/pyqt5-hello-world/
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtCore import QSize

class HelloWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(640, 480))
self.setWindowTitle("Hello world - pythonprogramminglanguage.com")

centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)

gridLayout = QGridLayout(self)
centralWidget.setLayout(gridLayout)

title = QLabel("Hello World from PyQt", self)
title.setAlignment(QtCore.Qt.AlignCenter)
gridLayout.addWidget(title, 0, 0)

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = HelloWindow()
mainWin.show()
sys.exit( app.exec_() )

The program starts in the main part.

We initialize Qt and create an object of the type HelloWindow.

We call the show() method to display the window.

pyqt hello world
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = HelloWindow()
mainWin.show()
sys.exit( app.exec_() )

The HelloWindow class inherits from the class QMainWindow.

We call its super method to initialize the window.

Several class variables are set: size and window title.

We add widgets to the window, including a label widget (QLabel) which displays the message “Hello World”.

The three steps

  • app = QtWidgets.QApplication(sys.argv) creates the application. There is exactly one per program.
  • w = QtWidgets.QMainWindow() creates the window, or a QWidget for something simpler.
  • w.show() makes it visible.
  • sys.exit(app.exec_()) hands control to Qt and keeps the program running.

Widgets are added to a layout, never placed with coordinates. A QVBoxLayout stacks them vertically and a QHBoxLayout puts them next to each other. The layout keeps things in place when the window is resized.

Install with pip install PyQt5. On Debian you can also use apt-get install python3-pyqt5.

If you want to try this yourself, the exercises on PyChallenge turn the same idea into a few short problems with instant feedback.