Putting a window in the middle of the screen takes three steps: get the screen size, get the window size, then move the window to the difference divided by two.

It has to run after show(), because before that the window has no size yet.

Understanding PyQt Window Geometry

It has to run after show(), because before that the window has no size yet.

First, we need to import QDesktopWidget, which is a crucial tool in determining screen properties:

from PyQt5.QtWidgets import QMainWindow, QLabel
from PyQt5.QtWidgets import QGridLayout, QWidget, QDesktopWidget

With this in place, the following code can be incorporated into the window creation function:

qtRectangle = self.frameGeometry()
centerPoint = QDesktopWidget().availableGeometry().center()
qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())

When the geometry of the window is called upon with:

qtRectangle = self.frameGeometry()

You can visualize qtRectangle by printing it out. For a window of 640x480 dimensions, this would output PyQt5.QtCore.QRect(0, 0, 640, 480).

In simpler terms, this output represents the window’s horizontal and vertical positions, width, and height. If you have specified different dimensions for your window, the output would adjust accordingly.

Centering the Window

With a grasp on the window’s geometry, the next step is positioning it in the screen’s center. To begin, ascertain the screen’s center using:

centerPoint = QDesktopWidget().availableGeometry().center()

Subsequently, move the application window to this central position with:

qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())

With these steps completed, your PyQt application window will start directly in the center of your computer screen, be it a desktop or a laptop.

Positioning elements like this, especially in a GUI-driven software, ensures an intuitive and seamless experience for the end-users.

The fastest way to learn this is to write it yourself. The PyChallenge exercises run in your browser, no install needed.