Remove QListWidgetItem: QListWidget::takeItem(item) vs delete item
Asked Answered
S

2

6

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.

Subchloride answered 27/6, 2017 at 14:43 Comment(0)
B
4

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.

Bashibazouk answered 27/6, 2017 at 14:57 Comment(3)
As removedItemWidget wasn't working for me I completely ignored it. Thanks for your quick answer @Mike.Subchloride
You are welcome :) . removeItemWidget() is not meant to remove the item from the QListWidget, it is there to remove a widget that has been previously set on item using setItemWidget().Bashibazouk
Yes, when I read the documentation I got it, but the initial thought when I saw the name was that it removed the QListWidgetItem ;)Subchloride
P
2

There is a substantial semantic difference related to returning or not the removed item:

docs say:

To remove an item (row) from the list entirely, either delete the item or use takeItem()

The final difference between takeItem and calling the destructor directly will be in calling takeAt instead of removeAt and, in the first case, being able to return the removed item while in the latter you just discard the thing entirely (take doesn't delete the item, you do it later)

Palmetto answered 27/6, 2017 at 15:0 Comment(2)
Thanks! As I already have the item takeItem adds nothing. It, of course, would be different if I'd only had the row index.Subchloride
Hello everyone, I have a quick question about this post: What would be the opposite? Meaning, from a list in QListWidget, how can I keep a single item only and erase the rest?Awaken

© 2022 - 2024 — McMap. All rights reserved.