ListView removeItem error

  • 5 Replies
  • 171 Views
ListView removeItem error
« on: 02 September 2021, 16:23:14 »
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 :

Code: [Select]
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

  • *****
  • 1625
    • View Profile
    • Texus's Blog
Re: ListView removeItem error
« Reply #1 on: 02 September 2021, 18:17:25 »
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)?

Re: ListView removeItem error
« Reply #2 on: 02 September 2021, 20:03:58 »
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:
Quote
listView->removeItem(0);

but this one does not and it throws the same error as mentioned earlier:
Quote
deleteBtn->onMousePress([&] {listView->removeItem(0);});
« Last Edit: 02 September 2021, 20:05:52 by cl3m »

Re: ListView removeItem error
« Reply #3 on: 02 September 2021, 22:12:53 »
Can you provide minimal reproducible sample?

*

texus

  • *****
  • 1625
    • View Profile
    • Texus's Blog
Re: ListView removeItem error
« Reply #4 on: 02 September 2021, 22:26:01 »
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.

Re: ListView removeItem error
« Reply #5 on: 03 September 2021, 01:12:39 »
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!
« Last Edit: 03 September 2021, 11:08:55 by cl3m »