title: How to remove widgets from layout in Qt
body: <p>I have a piece of code which does this: a method named <code>prepareUI</code> makes the UI ready to be able to load search results that are fed into it. A method named <code>onClear</code> that is called when the results that are already showing needs to be cleared. And a method named <code>populateSearchResults</code> that takes the search data and loads the UI with it. The container that holds the data is a publicly available pointer, since it is needed to clear the results from <code>onClear</code>:</p>
  
  <pre><code>void MyClass::prepareSearchUI() {
          //there may be many search results, hence need a scroll view to hold them
          fResultsViewBox = new QScrollArea(this);
          fResultsViewBox-&gt;setGeometry(28,169,224,232);
          fSearchResultsLayout = new QGridLayout();
  }
  
  void MyClass::onClear() {
      //I have tried this, this causes the problem, even though it clears the data correctly
      delete fSearchResultContainer;
      //tried this, does nothing
      QLayoutItem *child;
      while ((child = fSearchResultsLayout-&gt;takeAt(0)) != 0)  {
          ...
          delete child;
      }
  }
  
  void MyClass::populateWithSearchesults(std::vector&lt;std::string&gt; &amp;aSearchItems) {
      fSearchResultContainer = new QWidget();
      fSearchResultContainer-&gt;setLayout(fSearchResultsLayout);
  
      for (int rowNum = 0; rowNum &lt; aSearchItems.size(); rowNum++) {
          QHBoxLayout *row = new QHBoxLayout();
          //populate the row with some widgets, all allocated through 'new', without specifying any parent, like
          QPushButton *loc = new QPushButton("Foo");
          row-&gt;addWidget(loc);
          fSearchResultsLayout-&gt;addLayout(row, rowNum, 0,1,2);    
      }
      fResultsViewBox-&gt;setWidget(fSearchResultContainer);
  }
  </code></pre>
  
  <p>Problem is, when I call <code>onClear</code> which internally calls <code>delete</code>, it does remove all the results that were showing. But after that, if I call <code>populateWithSearchesults</code> again, my app crashes, and the stack trace shows this method as where it crashed.</p>
  
  <p>How do I fix this problem?</p>