Search code examples
c++qtqt5qlistwidget

Remove selected items from listWidget


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);
}

Solution

  • 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());