PySide6 script that shows an empty window
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# A script script that just displays
# an empty Qt6 window
import sys
from PySide6.QtWidgets import QApplication, QWidget
# 1 - Create a class inherited from QWidget
class Window(QWidget):
def __init__(self):
# If you don't init the superclass
# you get a run-time error
super().__init__()
if __name__ == '__main__':
# 2 - Create an instance of the QApplication class
# Make sure there isn't one already running.
if not QApplication.instance():
app = QApplication(sys.argv)
else:
app = QApplication.instance()
# 3 - Create an instance of the Window class
# and show() it
main_window = Window()
main_window.show()
# 4 - Start receiving events
sys.exit(app.exec())
This is a simple template script I use so I don’t have to remember the boilerplate code each time I want to use PySide6. The only thing it does is display an empty Qt window but it has all the elements of a Qt/PySide application nonetheless, So here’s the breakdown:
After the necessary imports
- Create a Python class that is a
QWidget
subclass.QWidget
is the base class of all Qt widget classes so you could useQPushButton
orQDialog
here instead. For more involved application that have toolbars, menubars etc you would useQMainWindow
that provides them out of the box. In your class’__init__()
you have to__init__()
the superclass (ie.QWidget
) or you get a runtime error.
In the main script code
-
Create a
QApplication
instance. This should be the first thing you do in your application/script. For non Qt Widget GUI application there isQGuiApplication
and for terminal/console applications there isQCoreApplication
.QApplication
is singleton so if you try to create it twice you getRuntimeError: Please destroy the QApplication singleton before creating a new QApplication instance.
(From now on I won’t be checking if theQApplication
instance exists as all the examples are quite simple but it’s something to be aware of) -
Create an object of your class (in the script
Window
) and.show()
it. (QWidget.show()
, well, shows it on the screen.) -
Use
QApplication.exec()
to start the application event loop. With this your application’s main windows is displayed on your screen and is able to process events. When you exit the application, for instance by pressing the window’s close buttonapp.exec()
returns and your application exits. That’s about it.