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

pyqt center screen

We add QDesktopWidget to the list of imports, having:

from PyQt5.QtWidgets import QMainWindow, QLabel, 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())

 

pyqt5 button
pyqt5 hello world

Leave a Reply

Your email address will not be published. Required fields are marked *