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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.