Search code examples
qtqwidget

Insert QWidget to an existing QBoxLayout at a particular position?


The questions says it all. Say I have a layout

mylayout
|-- widgetA
`-- widgetB

How do I insert a new widget to this tree?

mylayout
|-- widgetA
|-- widgetC
`-- widgetB

Solution

  • You should use QBoxLayout::insertWidget.

    The index is zero-based,
    it means the number of the widget before which the new one will be inserted.
    Or, you can think of it as  what the index of the inserted item will become.

    In this particular case you have:

    layout.addWidget(widgetA)
    layout.addWidget(widgetB)
    
    layout.insertWidget(1, widgetC)