THE CODE:
populateTable()
{
tableWidget->clearContents();
tableWidget->setRowCount(stringList.size());
for(int i = 0; i < stringList.size(); ++i)
{
tableWidget->setItem(i, 0, new QTableWidgetItem(stringList.at(i)));
}
}
THE PROBLEM:
The first time populateTable() is run, everything is fine. But the next consequent times, it runs significantly slower than before.
DISCUSSION:
After careful testing I suspect clearContents() to be the problem. Because simply changing the code from
tableWidget->clearContents();
to:
tableWidget->setRowCount(0);
fixes the problem, but now it makes another problem; Setting the row count to '0' does not seem to delete the heap allocated QTableWidgetItems, it just seems to leave ownership of the items, so it leaves a memory leak. (or at least i just think so...)
Qt's documentation in QTableWidget is rather vague, so i don't exactly know what clearContents() actually does. In the documentation it says "Removes all items not in the headers from the view" so that has left me asking, do the contents of the table just hide? does it get deleted? I'm not exactly sure. My theory is that clearContents() only hides the items and any next attempts to populate the table actually deletes and removes each item then allocates a new one to set on the table which in turn is an expensive operation.
Another interesting thing is that Qt's documentation on QTableWidget suggests that the proper way to populate a QTableWidget is to allocate a QTableWidgetItem on heap then set it on a table cell with setItem() just like i presented in the code above, which I find to be wierd...
IN SUMMARY:
Is there an alternate way to populate and repopulate a Qt table without having all of these problems? if not, is there a way to fix these problems?