Qt World Summit: Register Today!

How to set a layout in the center of a Widget?

  • I have a widget (stackedWidget). I put all buttons and labels for a page in a layout and sat the layout as widget's layout. But I want may buttons and labels (actually the layout) appear in the center or special location of widget.
    how can I set this?

  • you can use the horizontal spacers to do this. When the window is resized it will keep the button in the middle.


  • You don't position layouts, they fill their parent widgets. You can either use spacers, or simply calculate the center of your parent widget and move your child widget there manually.

    You have a geometry() function which returns the QRect of the parent widget, for QRect you have a center() function, which returns a QPoint which is the very center of the rectangle, which you can use for the child widget's move(QPoint&) function to move it to those coordinates.

    @// move child widget to its parent's geometry center

    note - parentWidget() is a function that returns a pointer to the parent widget, not the actual name of the parent widget

Log in to reply