PDA

View Full Version : How to remove QListItems via button click?



IndikaU
21st September 2011, 08:51
Hi,

I'm providing a QListWidget to get a list of custom values from the user as shown in the figure. The '+' is for adding & '-' is for removing item. To remove item user have to click an item on the list and the click '-' button. But this seems not working. I'm not sure whether I'm using the correct signals to achive this. Please help.

6869

The '-' enabled when user selects an item.

But click on '-' button do not remove the item from list. I'm keeping the currently selected item in a public variable to pass on remove method.



//Signals
connect(btnRemove, SIGNAL(clicked()), this, SLOT(RemoveFromList()));
connect(lstList,SIGNAL(itemActivated(QListWidgetIt em*)), this, SLOT(OnItemSelected(QListWidgetItem*)));


//Slots
void Designer::OnItemSelected( QListWidgetItem* item )
{
if ( item != NULL )
{
btnRemove->setEnabled(true);
p_CurrentItem = item; //this holds the user clicked item
}
}

void Designer::RemoveFromList()
{
if ( p_CurrentItem != NULL )
lstList->removeItemWidget(p_CurrentItem); //this don't remove the item, it stay in the list

if ( !lstList->count() )
btnRemove->setEnabled(false);
}

Lykurg
21st September 2011, 09:35
removeItemWidget? you want to remove an item not a widget! Just skip "Widget".

EDIT: and no need to save the selected item. You can get that every time by using QListWidget::currentItem().

Zlatomir
21st September 2011, 09:44
You can use takeItem (http://doc.qt.nokia.com/stable/qlistwidget.html#takeItem) (make sure you manually delete the returned pointer) or just call delete on the item pointer.

void Designer::RemoveFromList()
{
if ( p_CurrentItem != NULL )
delete p_CurrentItem; //this will remove the item
//...

//that ItemWidget removes something else, see here (http://doc.qt.nokia.com/stable/qlistwidget.html#removeItemWidget).

IndikaU
21st September 2011, 10:10
I could not find such method removeItem in QListWidget and code is not compiling. I'm using the latest Qt version.

Added after 14 minutes:

Isn't there any method to do this in one shot? To takeItem I have find the current row and pass it to get selected item.

Zlatomir
21st September 2011, 10:13
You already have the pointer, so just call delete

IndikaU
21st September 2011, 10:51
Thanks Zlatomir, I'm using the way u proposed.