Reputation: 365
I am trying to center my main window on my screen however neither of the two common ways are working. They both put it way too low and a little off center width wise. Here is what I have tried:
screen = QDesktopWidget().screenGeometry()
x = int((screen.width() - self.width()) / 2)
y = int((screen.height() - self.height()) / 2)
self.move(x, y)
self.setGeometry(QStyle.alignedRect(Qt.LeftToRight, Qt.AlignCenter, self.size(),
QDesktopWidget().availableGeometry()))
Note that right before doing this I set the width and height like this:
screen = QDesktopWidget().screenGeometry()
ww = int(screen.width() / 1.5)
wh = int(screen.height() / 2)
self.resize(ww, wh)
Upvotes: 1
Views: 3137
Reputation: 41
After trying all the solutions, I summarized the only correct way in pyside6. If you have called adjustsize() in the widget, you need to override the resizeEvent method to get the correct widget size:
def resizeEvent(self, event):
center = QtGui.QGuiApplication.primaryScreen().geometry().center()
self.move(center - self.rect().center())
return super().resizeEvent(event)
Upvotes: 0
Reputation: 1060
you are moving the topLeft of your widget to the screen center that's why it is not centered. You should take into account the size of your widget.
x = QApplication().desktop().screenGeometry().center().x()
y = QApplication().desktop().screenGeometry().center().y()
self.move(x - self.geometry().width()/2, y - self.geometry().height()/2)
Edit :
this works if self is the mainWindow. If it is a widget with a parent, move will move(x,y) will move your widget relatively to its parent. you should translate the coordinates below (global coordinates) to Parent coordinates, using :
QPoint QWidget.mapFromGlobal (self, QPoint)
Upvotes: 2