Search code examples
c++qtqtguiqtreewidgetqtreewidgetitem

Memory management for arguments to some Qt functions/constructors?


I want to add items to a QTreeWidget when a button is pressed. I'm using the following code in my program:

void MainWindow::on_training_addButton_clicked()
{
    countertest++;
    QStringList slist;
    slist << QString::number(countertest);
    ui->trainingDataTreeWidget->addTopLevelItem(new QTreeWidgetItem(slist)); //case 1

    //QTreeWidgetItem* item = new QTreeWidgetItem(slist); //case 2
    //ui->trainingDataTreeWidget->addTopLevelItem(item);
    //delete item;
}

In both cases I allocated dynamic memory for a QTreeWidgetItem. In the second case, I deleted it after passing it to addTopLevelItem(), but I'm worried Qt might need it later. What's the proper way to go about this?


Solution

  • The QTreeWidget destructor will take care of the deletion, and hence the class the life-cycle of the items. Just drop your external delete. IT would cause QTreeWidget trying to delete a dangling pointer, which would be the well-known double deletion crash.

    Here is the proof from the documentation as well as the source:

    Documentation

    QTreeWidget::~QTreeWidget()

    Destroys the tree widget and all its items.

    Source

    /*!
      \internal
    
      Destroys this tree model.
    */
    
    QTreeModel::~QTreeModel()
    {
        clear();
        delete headerItem;
        rootItem->view = 0; 
        delete rootItem;
    }
    
    /*!
      \internal
    
      Removes all items in the model.
    */
    
    void QTreeModel::clear()
    {
        SkipSorting skipSorting(this);
        beginResetModel();
        for (int i = 0; i < rootItem->childCount(); ++i) {
            QTreeWidgetItem *item = rootItem->children.at(i);
            item->par = 0; 
            item->view = 0; 
            delete item;
        }    
        rootItem->children.clear();
        sortPendingTimer.stop();
        endResetModel();
    }