View Full Version : QGridLayout: insert row in middle

18th May 2011, 21:18

I have a QGridLayout and after some action I would like to insert new rows at some specified row. Can I do this without manually moving all the widgets below?



Santosh Reddy
18th May 2011, 21:36
you can use

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

specify the "fromRow", all the widgets will be automatically adjusted.

18th May 2011, 23:05
to clarify (example)

I have a QGridLayout with already 20 rows full of widgets. Now I would like to insert a new row between row 9 and row 10. I think that this can not be done with the addWidget function?



30th May 2012, 20:41
I have the same question as the OP. Using the code in Santosh's response will replace whatever widgets are already in fromRow, fromColumn, not insert a new row/column. This is easy to do in Qt Designer, but I can't tell if there's a way to do it programmatically without manually moving every widget already in the QGridLayout.

31st May 2012, 07:23
There's no function to do it that I can see. For a simple grid of unspanned widgets it's trivial to move everything down a row to "open" a new row (or remove a row). Spanned widgets make it more difficult. However, if you need to do this a lot (for identical rows) then consider using a QVBoxLayout containing nested QHBoxLayouts for each row. You then have access to QBoxLayout::insertLayout() to insert new rows and QBoxLayout::takeAt() to remove them. Alternatively a QTableView/QTableWidget may be a viable option.

31st May 2012, 16:29
Good advice, thanks. Moving widgets manually didn't seem quite so trivial so I appreciate your suggestion of the QVBoxLayout. I thought at first that I had to use a QGridLayout to ensure that each row's components lined up as columns, but it just occurred to me that I can accomplish the same thing using widget size controls. I'll probably end up going that route.

Using QTableView would be the ideal, imo, but one of the columns has three different editable components and I couldn't figure out how to have a delegate create an editor for all three if they were in the same "cell." The model/view architecture has a very high learning curve when first getting started.