Search code examples
c++qtmemory-managementheap-memoryqtablewidget

Heap usage in QTableWidget in Qt


I'm trying to stress my program which basically updates with a different number of rows a QTableWidget

Every time I make some action I want to modify the size of the table, but before it if would like to clear it and with it its cell contents.

What I'm experiencing is that the heap as monitored from my resource monitor, only increases.

This is the part of code I run when I press a button in my app:

MyClass::updateTable(int nrows)
{
    ui->tableWidget->clearContents(); // this is to free the memory but the heap always grows
    for (int i=0; i<nrows; i++)
    {
        // I don't like this new I don't know when the destructor is called here!!
        QTableWidgetItem *item = new QTableWidgetItem();
        item->setText("SOMETEXT");
        ui->tableWidget->setItem(i,0,idItem);
    }
}

the number of rows as specified from int nrows is a very variable number ( from 10 to 10^5 ).

How do I clean the memory completely from the heap?


Solution

  • That new is necessary. The weird thing is that clearContents() should get rid of them. The other function you could use is the clear() function, but the only difference between those two is that clear will delete the headers first and then call clearContents(), which is the one that does the actual deletion of the items.

    In fact, look at the code for those functions:

    void QTableModel::clear()
    {
        for (int j = 0; j < verticalHeaderItems.count(); ++j) {
            if (verticalHeaderItems.at(j)) {
                verticalHeaderItems.at(j)->view = 0;
                delete verticalHeaderItems.at(j);
                verticalHeaderItems[j] = 0;
            }
        }
        for (int k = 0; k < horizontalHeaderItems.count(); ++k) {
            if (horizontalHeaderItems.at(k)) {
                horizontalHeaderItems.at(k)->view = 0;
                delete horizontalHeaderItems.at(k);
                horizontalHeaderItems[k] = 0;
            }
        }
        clearContents();
    }
    
    void QTableModel::clearContents()
    {
        for (int i = 0; i < tableItems.count(); ++i) {
            if (tableItems.at(i)) {
                tableItems.at(i)->view = 0;
                delete tableItems.at(i); //Your item should get deleted here
                tableItems[i] = 0;
            }
        }
        reset();
    }
    

    Are you sure this is where you're leaking?