Sometimes you want to position a window in the middle or center of the computer screen, with PyQt you can do that.

To center a Python PyQt window (put it in the center of the screen), we need to do a bit of trickery: we need to get the window properties, center point and move it ourself. At the start of the program, it will be in the center of the screen.

Related course: Create PyQt Desktop Appications with Python (GUI)

PyQt window properties

In this tutorial you will learn how to center a desktop window using PyQt. Before doing this, make sure you have PyQt installed correctly and know how to create a window.

The center of the screen is different on every computer, because the screen resolution is different. On a deskop with an 800x600 resolution the center isn’t the same as on a 1600x1200 resolution. Because of that, you need to get the screen size.

The first step is to add QDesktopWidget to the list of imports, having:

from PyQt5.QtWidgets import QMainWindow, QLabel
from PyQt5.QtWidgets import QGridLayout, QWidget, QDesktopWidget
Then include these lines of code in the window creation method:
qtRectangle = self.frameGeometry()
centerPoint = QDesktopWidget().availableGeometry().center()
qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())

The geometry of the window is then retrieved using:

qtRectangle = self.frameGeometry()
You can output qtRectangle using print(qtRectangle), this would return PyQt5.QtCore.QRect(0, 0, 640, 480).

In other words, the windows horizontal position, vertical position, the windows width and height.
If you created a window of a different width or height, those values would be different.

Move window to center

Now that we have all that, let’s put the window to the center of the screen. First get the center of the screen using this line of code:

centerPoint = QDesktopWidget().availableGeometry().center()
Then move our window to the center of the computer screen:
qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())

That’s it, the PyQt window is now in the center of your desktop (or laptop) screen.

If you are new to Python PyQt, then I highly recommend this book.

Download PyQt Examples