Search code examples
c++qtcentering

Qt C++ Display new window centered on old window


I have QWidget with button. When button is pressed, show new smaller window (Qwidget too). I want then new window is centered horizontal and veritcal on main window. Code which display new window is:

QWidget *wdg = new QWidget;
QPushButton *closeBtn = new QPushButton("Close");
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(closeBtn);
wdg->setLayout(layout);
wdg->show();
wdg->resize(400,200);

Solution

  • Use the move slot. For example:

    QPoint centerPoint = oldWidget->geometry()->center();
    
    newWidget->adjustSize();
    newWidget->move(centerPoint.x() - newWidget->width()/2, centerPoint.y() - newWidget->height()/2);
    

    You may consider using frameGeometry() instead of geometry().

    http://qt-project.org/doc/qt-5/application-windows.html#window-geometry

    Hope that helps.