How to release memory in QTreeWidget.



  • Hello I have a QTreeWidget, in which I add the items from a QThread it works well. Now If I am going to start QThread again, before it I called QTreeWidget::clear() , for clearing the tree to add new items. It works fine to clear the tree but not release the memory occupied by the QTreeWidgetItem. I tried

    QTreeWidgetItemIterator itr(treeWidget);
    while(*itr)
    {
    delete (*itr);
    ++itr
    }
    

    with QTreeWidget::clear();. So I want to know how can I release memory from QTreeWidget. Or How Can I properly delete QTreewidgetItem with memory release.


  • Moderators

    @rohit713 You should call deleteLater() on the item you want to free.
    Also you should never create/modify any UI related class instances in other thread than GUI thread!



  • hii @jsulm thanks for responding. I am not updating gui from QThread. I just emit a signal from QThread when I search the item. Then this signal is connected to QMainWindow slots for adding items in QTreeWidget using QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget)
    This new items called every time when thread got anything. Now the question is when I am going to start thread again. I have to release memory, consumed by QTreeWidgetItem. How can I use deleteLater().


  • Moderators

    @rohit713

    while(*itr)
    {
     (*itr)->deleteLater();
    ++itr
    }


  • @jsulm I tried this. But I got an error. class QTreeWidgetItem has no member named 'deleteLater' .



  • you are only deleting the root item and leaving its children untouched
    I would suggest

      while (treeWidget->topLevelItemCount()) {
        QTreeWidgetItemIterator itr(treeWidget,
                                    QTreeWidgetItemIterator::NoChildren);
        while (*itr) {
          delete (*itr);
          ++itr;
        }
      }
    


  • treeWidget->model()->removeRows(0,treeWidget->model()->rowCount()); clears the widget of all items and deletes them freeing the memory (see the sources if you don't believe me). Be aware that it's difficult to assess memory usage live in debug mode as the OS might keep the memory allocated for a while after you call delete


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.