Python

pyqt5 center window

To center a PyQt window, 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 Simple GUI Applications with Python and Qt

pyqt center screen

We add QDesktopWidget to the list of imports, having:

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

Include this 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()

We can output qtRectangle using print(qtRectangle),
this would return PyQt5.QtCore.QRect(0, 0, 640, 480)

Get the center of the screen using

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

Set it to the center
qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())

Previous Post Next Post

Cookie policy | Privacy policy | ©

PyQt