Remove selected items from listWidget
Asked Answered
C

2

31

How to remove selected items from a QListWidget?

I have tried write the following code, but it does not work.

QList<QListWidgetItem*> items = ui->listWidget->selectedItems();
foreach(QListWidgetItem item, items){
    ui->listWidget->removeItemWidget(item);
}
Cobia answered 21/8, 2014 at 2:24 Comment(2)
why item is not a pointer?Eldred
@wuqiang: I've changed item to *item. but still doesn't want to remove the items or any item.Cobia
E
45

One way to remove item from QListWidget is to use QListWidget::takeItem which removes and returns the item :

QList<QListWidgetItem*> items = ui->listWidget->selectedItems();
foreach(QListWidgetItem * item, items)
{
    delete ui->listWidget->takeItem(ui->listWidget->row(item));
}

Another way is to qDeleteAll :

qDeleteAll(ui->listWidget->selectedItems());
Epirogeny answered 21/8, 2014 at 4:41 Comment(8)
Good answer. Please note that the example here for qDeleteAll is illustrative.... it deletes only the items selected in the UI. qDeleteAll(ui->listWidget->items()); clears all entries. In general, qDeleteAll(someListOfValidItems); does the job.Cowardice
Thank you, but the first way occurs an error QModelIndex QListWidget::indexFromItem(QListWidgetItem*) const' is protected.Cobia
@LionKing You are right. you should use QListWidget::row. The answer is updated.Epirogeny
@Youda008 removeItemWidget only removes the widget set on the item. To remove an entire row you should use takeItem and also delete it to free memory. See: doc.qt.io/qt-5/qlistwidget.html#removeItemWidgetEpirogeny
@Nejat: That says manual. But i don't understand what removes the widget set on the item mean. What is widget set or what does it mean to set widget on the item ??Xylidine
@Xylidine removeItemWidget only removes the widget and the result is that an empty item without widget is left.Epirogeny
@Xylidine To make removeItemWidget(item) work, you should add in the following line delete(item)Cerebration
@Epirogeny - Your one-line answer (qDeleteAll(ui->listWidget->selectedItems());) is as relative today as it was when you gave it. Thank you.Alethiaaletta
W
9

To give a solution with removeItemWidget:

QList<QListWidgetItem*> items = ui->listWidget->selectedItems();

foreach(QListWidgetItem* item, items){
    ui->listWidget->removeItemWidget(item);
    delete item; // Qt documentation warnings you to destroy item to effectively remove it from QListWidget.
}
Wieren answered 3/1, 2018 at 15:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.