How to center mainWindow on the screen?
-
window managers can override client position hints, but
QWidget provide move() method.
-
OS:ubuntu22
QT6
I've tried various codes, but my mainWindow is always in the top left corner of my screen.@Tusen183
If you are running desktop under Wayland move etc,. will not work --- you cannot place the window, for now at least I don't know whether that can change in the future. You have to use Xorg in order to position the window on the desktop. See e.g. https://forum.qt.io/topic/142827/what-can-i-do-for-my-qtwidget-program-s-window-correctly-positioned-on-the-screen. Is this your situation? -
Well, there is one annoying thing that might prevent this: It is not possible to center the widget on the screen from within the constructor directly. Within the constructor the widget does not have a size, yet. Qt only gives proper values for the size after showing the widget. Only then will the layout geometry be computed. Calling show itself also does not show the widget immediately because several calls to
QWidget::update()
are collected into a single repaint. What we do (on Windows) is to queue another slot call into the event loop which centers the widget. The order of the show event and of our center-slot seem to work out.This is something to consider apart from other problems you might have. In the same vein I am not sure if a
move
call does anything when done before the widget is actually shown on the screen.PS: One thought to solve the ordering problem: connect a slot to the showEvent of the widget to center it on the first show. Maybe this will work.