12

QListWidget::selectedItems returns a list of QListWidgetItem, but the only function for removing an item that I found is takeItem, which accepts only indexes, and selectedIndexes function is protected.

3 Answers 3

25

Try

qDeleteAll(listWidget->selectedItems());
2
  • This seems to work, but from the help it seems qDeleteAll is just a generic function that calls delete on a range of objects. Won't the QListWidget still think it has those items?
    – sashoalm
    Aug 10, 2011 at 12:11
  • 4
    I found this link that explains why it works - a QListWidgetItem's destructor removes it from the QListWidget. Thanks for the answer!
    – sashoalm
    Aug 10, 2011 at 13:01
3

Iterate through the SelectedItemsList:

QList<QListWidgetItem *> itemList = widget->selectedItems();
for (int i=0; i<itemList.size(); i++) {
     widget->takeItem(widget->indexFromItem(itemList[i]));
}

I think

widget->removeItemWidget(itemList[i]);

may also work

1
  • 6
    From the Qt takeItem documentation: "Items removed from a list widget will not be managed by Qt, and will need to be deleted manually." So you should say delete widget->takeItem(...);
    – TonyK
    Aug 10, 2011 at 10:35
0

ui->listWidget->clear(); will do asof qt5

3
  • 1
    can you explain please?
    – Zahiro Mor
    Apr 3, 2016 at 14:05
  • 1
    ui->listWidget->clear(); will clear all the previous entries in the list widget
    – Dravigon
    Apr 5, 2016 at 14:09
  • In Qt5 QListWidget::clear() method properly works for the purpose of this question as @dravigon says :-)
    – tatsy
    Mar 2, 2017 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.