Skip to content

Instantly share code, notes, and snippets.

@saleph
Last active August 8, 2022 05:20
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save saleph/163d73e0933044d0e2c4 to your computer and use it in GitHub Desktop.
Save saleph/163d73e0933044d0e2c4 to your computer and use it in GitHub Desktop.
[qt5] center a window on screen
__author__ = 'tom'
import sys
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication
class Example(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.resize(250, 150)
self.center()
self.setWindowTitle('Center')
self.show()
def center(self):
# geometry of the main window
qr = self.frameGeometry()
# center point of screen
cp = QDesktopWidget().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()
sys.exit(app.exec_())
@grasboradas
Copy link

thanks man

@johnashu
Copy link

johnashu commented Jul 1, 2018

Nice :)

@sawaYch
Copy link

sawaYch commented Jan 8, 2020

Share my code (cpp version):
https://gist.github.com/sawaYch/f18d0832ce4620d2c32d17837465b26c

In latest qt5, seems:
QGuiApplication::primaryScreen();
is suggested to use, rather than :
QDesktopWidget().availableGeometry()

@rfiedorowicz
Copy link

I was just searching for that :D

@walid-kbb
Copy link

Thank you !

@zocker-160
Copy link

in case anyone is interested, I created a fork which gets rid of QDesktopWidget, which is the better way of doing this

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