How to center main window on screen?
I've looked high and low for this answer, so I'm not just throwing out a stupid question. I cannot find any information to center my main application window for the desktop. Just a standard program made in Designer, a mainform, and in the properties there is no such option like there is in VS-2005. I've also done searches here, and in the docs through Creator.
I have the code I've saved for years that works in standard C++, but it won't work in Qt. The handles are much different.
So, what's the secret?
PS: I saw the post by lovelypp already. It didn't work for me.
Re: How to center main window on screen?
Simply move the window to center then show it. This can be done by calling QWidget::show() then QWidget::move(int, int) or QWidget::move(const QPoint&). You can access information about current desktop screen geometry from QApplication::desktop()->screenGeometry().
The implementation should be like this.
Code:
int x = (screenGeometry.width()-mainWindow->width()) / 2;
int y = (screenGeometry.height()-mainWindow->height()) / 2;
mainWindow->move(x, y);
mainWindow->show();
Re: How to center main window on screen?
Quote:
Originally Posted by
viulskiez
Simply
move the window to center then
show it. This can be done by calling
QWidget::show() then
QWidget::move(int, int) or
QWidget::move(const QPoint&). You can access information about current desktop screen geometry from
QApplication::desktop()->screenGeometry().
The implementation should be like this.
Code:
int x = (screenGeometry.width()-mainWindow->width()) / 2;
int y = (screenGeometry.height()-mainWindow->height()) / 2;
mainWindow->move(x, y);
mainWindow->show();
My man, you got it! Oh how I thank you so much! I had to use "this" in the place of my MainWindow object which is not a good habit I know, but it works. I really thank you! :) :D
Re: How to center main window on screen?
This worked for me:
Code:
mainWindow
->setGeometry
(QStyle::alignedRect(Qt
::LeftToRight, Qt
::AlignCenter, mainWindow
->size
(), qApp
->desktop
()->availableGeometry
()));
Re: How to center main window on screen?
Makes my head hurt to read code with so many pieces of functionality crammed into a single line.
The only significant difference between your code and the previous, nearly 8 year old post is the use of "availableGeometry" rather than "screenGeometry" because it takes into account window system decorations that subtract from the usable screen area. This makes a small, but probably better result.
Re: How to center main window on screen?
These functions are obsolete:
Use QScreen instead:
Code:
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QScreen>
MainWindow
::MainWindow(QWidget *parent
) , ui(new Ui::MainWindow)
{
ui->setupUi(this);
move(QGuiApplication::screens().at(0)->geometry().center() - frameGeometry().center());
}