Crash course on Qt for Python

Let's write a simple application using our GUI library:

  1. Create a file named hello.py:
import sys
from PySide2.QtWidgets import QApplication, QWidget

app = QApplication(sys.argv)
window = QWidget()
window.resize(400, 400)
window.show()
sys.exit(app.exec_())
  1. Then run it using the following command:
(qt-venv) $ python hello.py

You will now see a blank window:

Let's go through this file to better understand Qt for Python:

import sys
from PySide2.QtWidgets import QApplication, QWidget

The sys import is from the standard Python library. This is required because we want to get the arguments from the command line when we launch this GUI application script. Then we import QApplication and QWidget from PySide2.QtWidgets.

What is PySide2? It comes from PySide, which is a Python binding for Qt 4. PySide2 is a Python binding for Qt 5. PySide was released in 2009 by Nokia (the former owner of Qt). Previously, Nokia failed to reach an agreement with Riverbank to make the PyQt license LGPL. Consequently, Nokia decided to create its own Python binding for Qt and named it PySide. The ownership of Qt moved from Nokia to the Qt company. The Qt company decided to beef up their effort to develop this Python binding for Qt, especially after Qt 5 was released.

There are two classes we import from PySide2.QtWidgets, which are QApplication and QWidget:

app = QApplication(sys.argv)

We create an instance of QApplication and pass the command-line argument. Most of the time, you would not use any command-line argument. You could pass the command-line argument if you want to tell the GUI application to use a different style or display text from right to left to cater to Arabic users, for example.

window = QWidget()
window.resize(400, 400)

With the window.show() method, we display the window object and then enter the main loop with app.exec_(). This is where the QApplication will dispatch all events from the desktop to the GUI. We wrap this process inside sys.exit() so we can get the return code from QApplication:

window.show()
sys.exit(app.exec_())