ListView removeItem error

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



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("Deadline", 100U);
    listView->addColumn("Done ?",50U);
    listView->addItem({ "Test", "03/09/2021", "No" });

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

What am I doing wrong here ?


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)?


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:

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


Can you provide minimal reproducible sample?


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.


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!