Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to remove children from a widget?



  • I'm having some trouble with crashes when removing child widgets from a parent widget.

    I'm creating a control that is used to display the content of a list of data objects in a way that will allow the user to select one of the objects and edit the data in it.

    I'm doing this by creating a scrollArea that contains a holder QWidget with a horizontal layout. I then create one of my MixerTrack UI widgets to wrap one mixer track for each track I want the user to edit and add it to my holder. Later, if the track list changes, I remove and delete the holder widget, create a new one, add it to my scrollarea and then create new MixerTrack widgets to wrap my new list data.

    This was working well for a while, but recently I've been getting crashes when I perform a delete on my holder widget. I'm not sure why and the stack trace provides no clue. There is nothing happening in the destructor of my widget that should be causing a problem. Commenting out the delete operation prevents the crash, but messes up the display because the old widgets aren't being removed anymore.

    Am I going about this right?

    void Mixer::updateTracks()
          {
          if (trackHolder) {
                trackAreaLayout->removeWidget(trackHolder);
                delete trackHolder;
                trackHolder = 0;
                }
    
          if (!_score)
                return;
    
          trackHolder = new QWidget();
          QHBoxLayout* holderLayout = new QHBoxLayout();
          trackHolder->setLayout(holderLayout);
    
          trackAreaLayout->addWidget(trackHolder);
    
          for (Part* part : _score->parts()) {
    ...
                MixerTrackPart* track = new MixerTrackPart(this, mti, expanded);
                holderLayout->addWidget(track);
    ...
          }
          update()
    }
    

  • Moderators

    hi @kitfox
    have tried it with deleteLater() istead of delete? It‘s the recommanded way for QWidget/QObject based classes, may already solve the issue.


  • Moderators

    hi @kitfox
    have tried it with deleteLater() istead of delete? It‘s the recommanded way for QWidget/QObject based classes, may already solve the issue.



  • @J.Hilk deleteLater() worked! Thanks so much.


Log in to reply