Reputation: 198188
This code works, but I wonder if there is any simpler way:
def center(self):
qr = self.frameGeometry()
cp = gui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
Upvotes: 19
Views: 25724
Reputation: 1144
It works for me:
from PySide2.QtGui import QGuiApplication
# ...
def center(self):
centerPoint = QGuiApplication.screens()[0].geometry().center()
self.move(centerPoint - self.frameGeometry().center())
Upvotes: 0
Reputation: 51
QDesktopWidget is deprecated. Use QScreen instead.
def centerWidgetOnScreen(self, widget):
centerPoint = QtGui.QScreen.availableGeometry(QtWidgets.QApplication.primaryScreen()).center()
fg = widget.frameGeometry()
fg.moveCenter(centerPoint)
widget.move(fg.topLeft())
Upvotes: 5
Reputation: 21
Just another "func-style" example. If you use it several times.
screen_center = lambda widget: QApplication.desktop().screen().rect().center()- widget.rect().center()
And every time in code:
widget.move(screen_center(widget))
Upvotes: 2
Reputation: 4869
self.move(QDesktopWidget().availableGeometry().center() - self.frameGeometry().center())
Upvotes: 9
Reputation: 217
just add this line to your main windows :
self.move(QtGui.QApplication.desktop().screen().rect().center()- self.rect().center())
Upvotes: 20
Reputation: 5487
No, it's the simplest way. Here is a snippet I've used in C++:
QRect desktopRect = QApplication::desktop()->availableGeometry(this);
QPoint center = desktopRect.center();
move(center.x() - width() * 0.5, center.y() - height());
Upvotes: 5