QTableWidget memory leak or not?

There is no leak, as

The table takes ownership of the item.

(From QTableWidget::setItem()).

Ownership here means that the QTableWidget will take care of deleting the item when its not longer needed, or the QTableWidget itself is destroyed. Ownership is usually documented in the Qt documentation (if not, I'd consider that a Qt bug).

Once setItem() returns from being called on the same cell, the previously set QTableWidgetItem will be deleted:

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    QTableWidget widget(2, 1);
    QTableWidgetItem* foo = new QTableWidgetItem("Foo");
    widget.setItem(0, 0, foo);
    qDebug() << foo->text(); //works
    widget.setItem(0, 0, new QTableWidgetItem("Bar")); //replaces foo with bar and deletes foo
    qDebug() << foo->text(); // Undefined (usually, crash)
    widget.show();
    return app.exec();
}

If you're on Linux, you can also verify the behavior by running above code (without the second qDebug()) in valgrind with --leak-check=full.


From the Qt documentation:

void QTableWidget::setItem ( int row, int column, QTableWidgetItem * item ) Sets the item for the given row and column to item. The table takes ownership of the item.

This indicates that Qt will manage the memory for the object as necessary.


It will delete properly when the you add Q-objects to the cells. I was pushing thousands of C-strings in cells and watched my memory blow up. Made my "raw text data" a QString and my problem was solved.