2. Adding widgets to a window
To add widgets to the window, we need to create the widgets and set their properties. In this case, we will first add a central widget to the window, then add a layout to the central widget, and finally add a button and a label to the layout.
Adding a layout
First we need to keep in mind that every QMainWindow
has to have a central widget. This usually is a generic QWidget
object. Next, we will add a layout to the central widget. A layout is a container that manages the position of child widgets. In this case, we will use a QVBoxLayout
('V' for 'vertical') to manage the position of widgets in our window. The newly added code is highlighted below:
Running the code above will still show an empty window, as we have added an empty layout to the window. Next, we will add widgets to this layout.
Adding widgets to the layout
We can create a button using the QPushButton
class and a label using the QLabel
class as follows:
button = QtWidgets.QPushButton()
button.setText("Click me!")
label = QtWidgets.QLabel()
label.setText("Hello, PySide6!")
If we simply add the above code to simple_gui.py
, the button and label will not be visible. This is because we have not added them to the layout. To add the button and label to the layout, we can use the addWidget()
method of the layout:
Let's add this code to simple_gui.py
and see how the window looks:
Running the above code will show a window with a label with a button that does absolutely nothing when clicked (which we will fix in the next step ).