效果如下:
1 """ 2 This program centers a window 3 on the screen. 4 """ 5 import sys 6 from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication 7 8 9 class Example(QWidget): 10 11 def __init__(self): 12 super().__init__() 13 14 self.initUI() 15 16 def initUI(self): 17 18 self.resize(250, 150) 19 self.center() 20 21 self.setWindowTitle('Center') 22 self.show() 23 24 def center(self): 25 26 # get a rectangle specifying the geometry of the main window 27 qr = self.frameGeometry() 28 29 # figure out the screen resolution of our monitor. 30 # And from this resolution, we get the center point 31 cp = QDesktopWidget().availableGeometry().center() 32 33 # set the center of the rectangle to the center of the screen 34 qr.moveCenter(cp) 35 36 # move the top-left point of the application window 37 # to the top-left point of the qr rectangle 38 self.move(qr.topLeft()) 39 40 41 if __name__ == '__main__': 42 43 app = QApplication(sys.argv) 44 ex = Example() 45 sys.exit(app.exec_())