To remove a given QListWidgetItem* item
from a QListWidget* lst
I can use following code (taken from this answer):
delete lst->takeItem(lst->row(item)); // method 1
On the other hand, if I just destroy the item, it is also removed from the list (at least it disappears from the QListWidget
).
delete item; // method 2
QListWidget
documentation indicates using takeItem
but doesn't mention anything about deleting the item (QListWidgetItem
doesn't have any information neither).
To remove items from the list, use takeItem().
Is there any difference between using method 1 (takeItem
and then delete it) and method 2 (directly delete the item)? Maybe a memory leak I'm missing, a signal that is not emitted, etc? I mean, it seems easier to just delete the item (if you have it, of course) rather than searching for it.
The following line from the docs answers your question:
To remove an item (row) from the list entirely, either delete the item or use
takeItem()
.
This means that there is no difference between taking the item then deleting it, or deleting it directly.
takeItem()
just removes ownership from the item, so that you have the chance to do anything with it (maybe use it in another QListWidget
). If you just want to remove the item, you can just delete it and the destructor will take care of removing ownership.