Centering window¶
Let’s place the window in the center of the screen as shown above.
Example¶
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 appears on the center of the screen.
Description¶
self.center()
Centering the window works through center() method.
qr = self.frameGeometry()
Use frameGeometry() method to get the location and size of the window.
cp = QDesktopWidget().availableGeometry().center()
Find out the center location for the monitor screen you use.
qr.moveCenter(cp)
Move the rectangular position of the window to the center of the screen.
self.move(qr.topLeft())
Move the current window to the rectangle(qr) position that you moved to the center of the screen. As a result the center of the current window matches the center of the screen and makes the window appear in the center.
Prev/Next
Prev : Creating a toolbar
Next : Displaying date and time