Qt QGridLayout automatically centers (moves) items to the middle.

Phil picture Phil · Dec 25, 2012 · Viewed 14.4k times · Source

I have a QHBoxLayout on my form with 3 layouts added to it. The second one has the items concerning my question.

I have a QVBoxLayout on the second pane of the main layout (the QHBoxLayout). This QVBoxLayout has a QScrollArea added to it with addWidget.

This QScrollArea is parent to a QWidget called "scrollContents" which in turn contains a QGridLayout.

I am adding a custom created widget to this QGridLayout which has a fixed height. We can consider this 100px for now.

If this QGridLayout has items, of which the total height is less than the form itself, it centers these widgets vertically with same amount of space between them.

If there is one single widget, it appears right in the middle. But I would like them to be listed from top to bottom.

Ex.: [### represents the area of QScrollArea in which there's a QWidget with the QGridLayout.

   OK      ->   DESIRED    -> NOT DESIRED AND WHAT HAPPENS
##########    ##########               ##########
# |item| #    # |item| #               #        #
# |item| #    #        #               #        #
# |item| #    #        #               #        #
# |item| #    #        #               # |item| #
# |item| #    #        #               #        #
# |item| #    #        #               #        #
# |item| #    #        #               #        #
##########    ##########               ##########
  |item|
  |item| 
  |item|

Basically: If there's space for 9 "rows", when a single one item is added it appears in the middle at the location of 5th. If there is 9 or more, they appear as they should. If there is 8 or less, their space in-between is expanded to center them all.

How can I solve this?

Thank you.

Answer

Oleg Shparber picture Oleg Shparber · Dec 25, 2012

QGridLayout::addWidget() has alignment parameter. The following code works for me:

gridLayout->addWidget(new QPushButton("Button"), 0, 0, Qt::AlignTop);