QListWidget delete selected item
-
Welcome, how can I delete selected item in list? I try something like this but it doesn't seem to work.
void MyWindow::on_pushButtonDelete_clicked() { // Delete selected item in list ui->listWidgetMy->currentItem()->takeItem(); }
Thank you for detailed answers.
-
You may use this code to remove:
QListWidgetItem *it = ui->listWidget->takeItem(ui->listWidget->currentRow()); delete it;
Keep in mind that "takeItem" does not delete the object.
-
currentItem()
is not necessarily selected. for example: if you select items 2,4,5 and then deselect item 4currentItem()
will be 4 but the selected items are 2 and 5To remove the row completely:
QModelIndexList selectedList = ui->listWidgetMy->selectionModel()->selectedIndexes(); // take the list of selected indexes std::sort(selectedList.begin(),selectedList.end(),[](const QModelIndex& a, const QModelIndex& b)->bool{return a.row()>b.row();}); // sort from bottom to top for(const QModelIndex& singleIndex : selectedList) ui->listWidgetMy->model()->removeRow(singleIndex.row()); // remove each row
-
Hi, friend, welcome devnet.
if i were you. i will following the steps to find my answer.
- I used the
QListWidget
. I will searchQListWidget
in Qt help manual. - If i want to delete the selected item, i must get them first. so, i search
select
key in manual.or function list. i find the followinginfo.
selectedItems() const : QList<QListWidgetItem *> //Returns a list of all selected items in the list widget.
- Then, i must to delete or remove them form
QListWidget
. so, i search the 'delete' or 'remove' key in manual. Nothing? Why didn't have the 'delete item' or 'remove item' function? Think...Think...I watched all functions ofQListWidget
. I foundtakeItem
.
QListWidgetItem *QListWidget::takeItem(int row) /*Removes and returns the item from the given row in the list widget; otherwise returns 0. Items removed from a list widget will not be managed by Qt, and will need to be deleted manually. See also insertItem() and addItem().
- Now, I got the list of items i want to delete, and, i take every it in for. **But Note, I should delete it. **
for(...){ takeItem(item); delete item; }
This is my way how to find the answer to shared for you.
There are ways, There is one question. we should to learn the ways not to remeber the answer.
- I used the
-
@kishore_hemmady said in QListWidget delete selected item:
how can i achieve this by selecting the check Box rather than selecting the list content?
for(int i=ui->listWidget->model()->rowCount()-1;i>=0;--i){ if(ui->listWidget->model()->index(i,0).data(Qt::CheckStateRole).toInt()==Qt::Checked) ui->listWidgetMy->model()->removeRow(i); }