Let's write a simple application using our GUI library:
- 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_())
- 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:
- QApplication is a class designed to manage GUI application flows and its settings. It checks your desktop configuration, such as the font, and passes it to the GUI. It also understands the incoming objects from the desktop, for example, when you copy text from the text editor and paste it to the GUI application. There can only be one QApplication in your GUI script:
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.
- The second class we import from PySide2.QtWidgets is QWidget. This is the base class of any widget you will ever use when creating a GUI application, such as a button, a text field, a slider, or a label. If you construct the base class, you would get an empty window. This is similar to UIView in iOS. We then resize the window:
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_())