from PyQt5.QtWidgets import QApplication, QDesktopWidget app = QApplication([]) desktop_screen = QDesktopWidget().screenGeometry() print(desktop_screen.width()) #prints the horizontal screen size print(desktop_screen.height()) #prints the vertical screen size
from PyQt5.QtWidgets import QApplication, QDesktopWidget, QMainWindow, QPushButton class CenteredWidget(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Centered Widget') button = QPushButton('CLOSE', self) button.clicked.connect(self.close) self.resize(250, 150) self.center() def center(self): desktop_screen = QDesktopWidget().screenGeometry() x = (desktop_screen.width() - self.width()) / 2 y = (desktop_screen.height() - self.height()) / 2 self.move(x, y) app = QApplication([]) centered_widget = CenteredWidget() centered_widget.show() app.exec_()In the first example, we have imported the required modules, created a QApplication instance, and created a QDesktopWidget instance to get the screen size. In the second example, we have created a QMainWindow subclass and added a QPushButton to it. We have also defined a center() method to place the widget in the center of the desktop screen. We have instantiated the subclass, called the center() method to center the widget and displayed it using app.exec_(). The package library used here is PyQt5.QtWidgets.