QGridLayout* layout = new QGridLayout;
int currentRow = 0;
int cb1row = currentRow;
QCheckBox cb1 = new QCheckBox("cb1");
layout->addWidget(cb1, currentRow++, 0, 1, -1, Qt::AlignTop);
QCheckBox cb2 = new QCheckBox("cb2");
layout->addWidget(cb2, currentRow++, 0, 1, -1, Qt::AlignTop);

How can I dynamically insert some other widgets later on? Say if I would like to insert another checkbox after cb1. I tried below, but both new checkbox and cb2 are overlapped. Is there any way to auto push the rest widgets one row down when inserting?

int newCbRow = cb1row + 1;
QCheckBox newCb = new QCheckBox("cb3");
layout->addWidget(newCb , newCbRow, 0, 1, -1, Qt::AlignTop);

Or should I use another kind of layout which has the capability to append/insert widgets by index/row#?

有帮助吗?

解决方案

You have a few solutions, these come to mind:

  • If it is as simple case as your question shows, then just remove cb2 from the QGridLayout using QLayout::removeWidget() and re-add it to new position.
  • Instead of using QGridLayout directly for rows, make each row a nested QHBoxLayout (main layout can be QGridLayout with just 1 column, or QVBoxLayout). It supports inserting in the middle.
  • If you want to use QGridLayout, and real use case is more complex than shown in the question, then just re-create the layout from scratch when you need to insert widgets. Write a method, which deletes current layout (if it exists, ie. not first call), then creates a new layout and puts all widgets in it. Then you call this from constructor, and also when you add widgets, without duplicating code.

其他提示

If your widgets do not span more than one cell you can move all widgets at and below the cell which shall be added to down one row. Then you have one row free that you can add a widget to. Personally, I tend to use nested layouts QHBoxLayout and QVBoxLayout because they give more freedom in many cases.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top