Remove selected items from listWidget

2019-04-04 14:32发布

How to remove selected items from qlistWidget.

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

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

Now, how to remove the items that I selected from the qlistWidget ?

2条回答
成全新的幸福
2楼-- · 2019-04-04 14:45

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.
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-04-04 15:04

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());
查看更多
登录 后发表回答