c++linuxqtwindow-position

Qt MainWindow Position in Linux


I have a situation where my main window opens in the upper left of the monitor, only under linux. It looks quite strange, especially when a informational popup appears at program start, that is properly centered where mainwindow is on Mac and Windows! Screenshot below:

enter image description here

How can I fix this Linux issue?


Solution

  • You can use setGeometry to position the window in center. It can be like :

    #include <QStyle>
    #include <QDesktopWidget>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
    
        w.setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, w.size(), qApp->desktop()->availableGeometry()));
    
        w.show();
    
        return a.exec();
    }
    

    An other way :

    MainWindow w;
    
    QDesktopWidget *desktop = QApplication::desktop();
    
    int screenWidth = desktop->width();
    int screenHeight = desktop->height();
    
    int x = (screenWidth - w.width()) / 2;
    int y = (screenHeight - w.height()) / 2;
    
    w.move(x, y);
    w.show();