0

Run it! You will now see your window. Qt automatically creates a window with the normal window decorations and you can drag it around and resize it like any window.

Our window, as seen on Windows, macOS and Linux.

Let’s step through the code line by line, so we understand exactly what is happening.

First, we import the PyQt classes that we need for the application. Here we’re importing QApplication, the application handler and QWidget, a basic empty GUI widget, both from the QtWidgets module.

The main modules for Qt are QtWidgetsQtGui and QtCore.

For this demo we’re using a QPushButton. The core Qt widgets are always imported from the QtWidgets namespace, as are the QMainWindow and QApplication classes. When using QMainWindow we use .setCentralWidget to place a widget (here a QPushButton) in the QMainWindow — by default it takes the whole of the window. We’ll look at how to add multiple widgets to windows in the layouts tutorial.

Our QMainWindow with a single QPushButton on Windows, macOS and Linux.

The window is currently freely resizable — if you grab any corner with your mouse you can drag and resize it to any size you want. While it’s good to let your users resize your applications, sometimes you may want to place restrictions on minimum or maximum sizes, or lock a window to a fixed size.

In Qt sizes are defined using a QSize object. This accepts width and height parameters in that order. For example, the following will create a fixed size window of 400×300 pixels.

Our fixed-size window, notice that the maximize control is disabled on Windows & Linux. On macOS you can maximize the app to fill the screen, but the central widget will not resize.