PyQt5 window to the center of the screen

Let's put the window in the center of the monitor screen. The program creates a PyQt5 GUI window on your desktop, which is the positioned at exactly the center of the screen.

Related course: Create Desktop Apps with Python PyQt5

Example window center

The program below works with Python 3, it puts the window on the center of the screen.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget

class MyApp(QWidget):

def __init__(self):
        super().__init__()
        self.initUI()

def initUI(self):
        self.setWindowTitle('Centering')
        self.resize(500, 350)
        self.center()
        self.show()

def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

The window will show in the center of the screen.

Description

self.center()

The center() method allows the window to be located in the center of the screen.

qr = self.frameGeometry()

Use the primeGeometry() method to get information about the location and size of the window.

cp = QDesktopWidget().availableGeometry().center()

Determine the center position of the monitor screen you are using.

qr.moveCenter(cp)

Move the rectangular position of the window to the center of the screen.

self.move(qr.topLeft())

Moves the current window to the position of the rectangle (qr) that moved to the center of the screen. As a result, the center of the current window will match the center of the screen, so that the window will appear in the center.

Related course: Create Desktop Apps with Python PyQt5