Search code examples
qtlayoutsplitter

How to add a layout to QSplitter?


I have a vertical splitter with 3 Columns. Inside of the second one I want to have some Buttons aligned horizontally and below these buttons there is a ListWidget. The problem is, that I would want to have a vertical Layout (VBoxLayout) inside the second column of the splitter to align the buttons above the List. But the Splitter only accepts addWidget(...), not addLayout(...). So I can't add the VBoxLayout inside of the splitter. What's the correct way to put the button above the ListWidget inside of the splitter?

+--------------------------------------+
| column1 |    column2       | column3 |
|  .....  | button1,button2, | ....... |
|  .....  | ListElement1     | ....... |
|  .....  | ListElement2     | ....... |
|  .....  | ListElement3     | ....... |
|  .....  |  .........       | ....... |
+--------------------------------------+

Solution

  • Splitter only accepts addWidget(...), not addLayout(...)

    That sentence gives the solution. Create a new QWidget object and set a QVBoxLayout to it. Add what you want to the layout and add the widget to the splitter.

    In your case:

    auto *splitter = new QSplitter(this);
    auto *widget = new QWidget(this);
    auto *layoutColumn = new QVBoxLayout(widget);
    auto *layoutButtons = new QHBoxLayout();
    auto *btn1 = new QPushButton(tr("Button 1"), this);
    auto *btn2 = new QPushButton(tr("Button 2"), this);
    auto *list = new QListWidget(this);
    
    layoutButtons->addWidget(btn1);
    layoutButtons->addWidget(btn2);
    
    layoutColumn->addLayout(layoutButtons);
    layoutColumn->addWidget(list);
    
    ...
    splitter->addWidget(widget);
    ...