ListView removeItem error

Started by cl3m, 02 September 2021, 16:23:14

cl3m

Hello,

I'm trying to create a button that deletes the selected item in a , but whenever I click on the button, listView->removeItem() throws an std::out_of_range error in memory. Here is my code :

tgui::ListView::Ptr listView = gui.get<tgui::ListView>("list");
    tgui::Button::Ptr deleteBtn = gui.get<tgui::Button>("deleteBtn");

    listView->addColumn("Title",240U);
    listView->addColumn("Deadline", 100U);
    listView->addColumn("Done ?",50U);
    listView->addItem({ "Test", "03/09/2021", "No" });

    listView->onItemSelect(&updateGui,std::ref(gui)); // updates other widgets
    deleteBtn->onMousePress([&] {
        listView->removeItem(listView->getSelectedItemIndex());});
   
    gui.mainLoop();

What am I doing wrong here ?
Thanks

texus

What is the value of listView->getSelectedItemIndex() inside the onMousePress function? Is there any chance that it is -1 when it throws (which is the case when no item is selected)?

cl3m

#2
getSelectedItemIndex() returns 0, which is okay because my ListView only  contains 1 item.
I believe that the issue comes from the removeItem() method when encapsulated in a signal:
for instance, with 1 item in the ListView, this piece of code works:
QuotelistView->removeItem(0);

but this one does not and it throws the same error as mentioned earlier:
QuotedeleteBtn->onMousePress([&] {listView->removeItem(0);});

Kvaz1r

Can you provide minimal reproducible sample?

texus

removeItem apparently shouldn't throw out_of_range even when a wrong index is provided, but I did notice something else in the code that could go wrong.

removeItem() will remove the selected item and thus cause the selection to change. The onItemSelect is triggered halfway through the removeItem() call, so your updateGui is called while removing the item. I'm guessing the updateGui function probably does something with the list view which causes the error.

cl3m

#5
Problem solved! updateGui() was actually messing things up as you mentioned, because it was reading the selected item text to update other widgets. The issue was simply fixed by testing if getSelectedItemIndex() returns -1 at the beginning of updateGui().

Thanks for your help @texus and @Kvar1z!