Center Main Window on Screen in Qt 6

Center Main Window on Screen in Qt 6

When developing applications using the Qt framework, one common requirement is to center the main window of the application on the screen. This seemingly simple task can be challenging, especially for developers new to Qt. Fortunately, Qt provides straightforward method to achieve this. This tutorial shows how to center main window on screen in Qt 6.

This code demonstrates how to create a simple Qt application with a main window that is centered on the screen. Inside the main function, the application initialization process is initiated, followed by the creation of a new window widget with a predefined size. Then, the position for centering the window on the screen is computed using details about the screen geometry and the window's frame geometry.

#include <QApplication>
#include <QWidget>
#include <QScreen>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    auto *window = new QWidget();
    window->resize(900, 600);
    window->move(window->screen()->geometry().center() - window->frameGeometry().center());
    window->show();

    return QApplication::exec();
}

Leave a Comment

Cancel reply

Your email address will not be published.