A widget contained in more than one cell in a QGridLayout is not centered

Darkgaze picture Darkgaze · Jan 11, 2013 · Viewed 17.2k times · Source

The question sais it all.

I have a 5 x 3 grid.

It looks like this

row 0:  buttonA--buttonA--buttonA   nothing   buttonB--buttonB--buttonB

row 1:  empty row

row 2:  buttonC  nothing  buttonD   nothing   buttonE  nothing  buttonF     

In the spaces where there is nothing in the whole column or row the minimumRowHeight and all of those settings would work. Right?

Well. The button A and button B (and the rest), never get centered over those 3 cells they share. NEVER. doesn´t matter what i write on the parameters for the layout.

I erased the code because it finally got it using a Vertical Layout, and inside, two horizontal layouts. Those get centered that way. But i would like to position them better.

What doesn´t work is when adding a widget, using:

addWidget( widget, 0,0 , 2,0 , Qt::AlignHCenter ); not even AlignCenter works.

How to make it centered or aligned to the right?

Thanks!

Answer

Tim Meyer picture Tim Meyer · Jan 15, 2013

The syntax of QGridLayout::addWidget() is like this:

void QGridLayout::addWidget ( QWidget * widget, int fromRow, int fromColumn, int rowSpan, int columnSpan, Qt::Alignment alignment = 0 )

with the description:

This version adds the given widget to the cell grid, spanning multiple rows/columns. The cell will start at fromRow, fromColumn spanning rowSpan rows and columnSpan columns.

This means your line

addWidget( widget, 0, 0, 2, 0, Qt::AlignHCenter ); 

has fromRow = 0, fromColumn = 0, rowSpan = 2 and columnSpan = 0. This means it starts from row 0 and spans over two rows, i.e. it will be in row 0 and 1 (Note: Two rows in total, not two additional rows). Also it starts from column 0 with a span of 0 which I think means the column span is ignored.

So what you really want should be:

addWidget( widget, 0, 0, 0, 3, Qt::AlignCenter );

You might have to experiment with the alignment a bit.