Search code examples
qtqsplitter

How to replace a widget in Qsplitter with another?


I have one splitter and two widgets... i want to replace the first widget with a splitter, and put in it the first widget and another widget withe the same arrangement (in runtime)

PS: i can't drop the first widget from the splitter


Solution

  • You don't need a new splitter for the replace since QSplitter can handle more than 2 widgets. Say we have two widgets in a splitter:

    QSplitter *splitter = new QSplitter(this);
    setCentralWidget(splitter);
    
    QTextEdit *widget0 = new QTextEdit;
    QTextEdit *widget1 = new QTextEdit;
    
    splitter->addWidget(widget0);
    splitter->addWidget(widget1);
    

    Now we can put a third widget between these two with:

    QTextEdit *widget2 = new QTextEdit;
    splitter->insertWidget(1, widget2);
    

    Now we have the three widgets and two splitters between them in the order of widget0, widget2, widget1.

    Update:

    If the orientation of the second splitter is different, than:

    QSplitter *splitter2 = new QSplitter;
    splitter2->setOrientation(Qt::Vertical);
    QTextEdit *widget2 = new QTextEdit("2");
    splitter2->addWidget(widget0);
    splitter2->addWidget(widget2);
    splitter->insertWidget(0, splitter2);
    

    Result:

    enter image description here