Search code examples
c++qtqsplitter

Remove Widget from QSplitter


A long time ago, someone asked the same question. How to remove...

This was the answer:

When you hide() a child its space will be distributed among the other children. It will be reinstated when you show() it again.

I've tried the QSplitter::hide(),show(),update() functions and also delete. Nothing worked.

//class.cpp

void PlainView::addComponent(QWidget *widget)
{
  qDebug() << _splitOne->widget(1);

  //delete current widget on index 1
  delete _splitOne->widget(1);
  //add new widget on index 1
  _splitOne->addWidget(widget);

  qDebug() << _splitOne->widget(1);
}

//output
QObject(0x0)  
QTextEdit(0xa0f580

The first widget was deleted and the new widget was added. But I can't see the new widget.

Has anyone an idea?


Solution

  • don't use delete but instead use deleteLater() and you'll need to remove the old widget first:

    void PlainView::addComponent(QWidget *widget)
    {
      qDebug() << _splitOne->widget(1);
      QWidget *old = _splitOne->widget(1);
    
      // deparenting removes the widget from the gui
      old->setParent(0);
      //delete current widget on index 1
      old->deleteLater()
    
      //add new widget on index 1
      _splitOne->insertWidget(1,widget);
      widget->show();
    
      qDebug() << _splitOne->widget(1);
    }