Search code examples
qtqt-designer

How to centralize widget automatically with qt designer?


I am creating an application in full screen, however when editing in qt design there is no such option. So when I center the widget on the qt designer it looks like this:

enter image description here

It looks like it was centered, but it centered to the standard window size:

enter image description here

Now look what happens when I increase the size of the window:

enter image description here


Solution

  • You are almost there. If you add 2 vertical spacers, put them and your horizontal layout to a vertical layout and finally put everything on mainwindow to a grid layout, you'll achieve what you are looking for. It looks like so: MainWindow preview Widget tree

    This way the widget is placed right in the center of your window no matter the size of the window. Just make sure the sizeType property of spacers are set to Expanding. Window

    Alternatively, you can achieve the same functionality by overriding QMainWindow::resizeEvent. Something like this:

    //In your .h file
    protected:
        void resizeEvent(QResizeEvent *event) override;
    //In your .cpp file
    void MainWindow::resizeEvent(QResizeEvent *event)
    {
        ui->pushButton->setGeometry(this->width()/2 - ui->pushButton->width()/2,
                                    this->height()/2 - ui->pushButton->height()/2,
                                    ui->pushButton->width(),
                                    ui->pushButton->height());
    }
    

    It requires for more coding, but allows for more flexibility.