PDA

View Full Version : Procorrect way to remove checked elements from a QListWidget



franco.amato
22nd September 2020, 02:07
Hi to all,
this seems to be a simple task but is error prone.
I have a QListWidget where I insert some items that have the chequeable flag. At some point I need to remove ( delete ) from the list only the checked items.
is not possible to use a for loop due to the fact that the list size change every time an item is removed. I also tried using qDeleteAll and the findItems but how to crete a pattern with only checked items?
Thanx in advance,
Franco

^NyAw^
22nd September 2020, 08:41
Hi,

You have to do a "while" loop until no deletion needs to be performed. Into loop you have to search the first item to be deleted. When no item needs to be deleted you can exit the loop.

franco.amato
22nd September 2020, 15:26
Hi,
thanx. It can be possible to have a small example or preudo code?
Thanx

^NyAw^
22nd September 2020, 16:00
Hi,

I hope something like this will work:



bool bDeletion = true;
while (bDeletion)
{
//Search element to delete. We have to get the number of elements every start of searching
int i=0;
bool bFound = false;
int iNumElements = m_qListWidget.count();
while (!bFound && (i<iNumElements))
{
if (m_qListWidget.at(i)->elementHasToBeDeleted()) //Implement your method
bFound = true; // "i" points to element to delete
else
i++; //Jump to next element
}

//If we have found one element to delete, just delete it
if (bFound)
delete m_qListWidget.takeAt(i);
//If we have not found any element to delete just exit the loop (job finished)
else
bDeletion = false;
}


As I supose that no many items are there on the list, the search of an item to be deleted starts every time from item 0. You could save the deletion position and start the search againg from this value but you have to get the number of items again and check that it is not out of bounds.

Lesiok
22nd September 2020, 17:01
It couldn't be easier :

int i=0;
int iNumElements = m_qListWidget.count();
while (i<iNumElements)
{
if (m_qListWidget.at(i)->elementHasToBeDeleted()) //Implement your method
{
delete m_qListWidget.takeAt(i);
iNumElements--;//Because we have removed one item from the list
}
else
{
i++; //Jump to next element
}
}