Search code examples
c++qtqcombobox

How to position an added widget to a layout based on another widget in the same layout?


In my GUI, I would like to add a QComboBox to a verticalLayout programmatically based on a a signal triggered by specific action. The following code works fine and the widget is added:

QComboBox* userOptions = new QComboBox();
ui->verticalLayout_13->addWidget(userOptions);

However, this way the widget is always added to the end of the layout.

My question is: how to position the added QComboBox to the verticalLayout in alignment to another widget in the same layout ? (i.e.: above the "Go" push button for example)


Solution

  • There doesn't seem to be a way to explicitly insert an item in a layout where you want it to be.

    You have a few choices to achieve that the "hard" way:

    • use QLayout::takeAt(int index) to take all items after the index you want to insert at, insert your item, then insert back the taken items.
    • create a placeholder widget which you can use to reserve an index in the layout, then you don't insert the item in the layout, but in a layout nested inside the placeholder widget. Without an item, the placeholder widget takes no space, and expands to accommodate whatever is put into it.
    • implement your own QLayout subclass which supports inserting at a specific index. There are several functions you will have to implement.

    EDIT: An omission on my end, as Kuba Ober noted, most of the concrete layout implementations support inserting at a specific index, for example QBoxLayout derived have insert methods which pass an index as a parameter.