Skip to content

Instantly share code, notes, and snippets.

@zocker-160
Forked from saleph/centering.py
Last active April 11, 2022 20:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zocker-160/6d103bba7575ed6dc5ca0ffc891f092c to your computer and use it in GitHub Desktop.
Save zocker-160/6d103bba7575ed6dc5ca0ffc891f092c to your computer and use it in GitHub Desktop.
[qt5] center a window on screen
__author__ = 'tom'
import sys
from PyQt5.QtWidgets import QWidget, QApplication
class Example(QWidget):
def __init__(self, app: QApplication):
super().__init__()
self.app = app
self.init_ui()
def init_ui(self):
self.setWindowTitle('Center')
self.resize(250, 150)
def center(self):
# geometry of the main window
qr = self.frameGeometry()
# center point of screen
cp = self.app.primaryScreen().availableGeometry().center()
# move rectangle's center point to screen's center point
qr.moveCenter(cp)
# top left of rectangle becomes top left of window centering it
self.move(qr.topLeft())
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Example(app)
ex.center()
ex.show()
sys.exit(app.exec_())
@zocker-160
Copy link
Author

updated to eliminate the use of QDesktopWidget

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment