Search code examples
c++imgui

How to use vector<MyObject> with ImGui::ListBox?


I'm trying to display a vector of objects in a listbox that will be rendered dynamically in every frame.

This is my class and I want to display every attribute later in the listbox:

class Waypoint {
public:
    int x, y, z;
    char action;
};

What I'm trying now as I don't really know is this:

Waypoint wp1;
wp1.action = 'R';
wp1.x = 100;
wp1.y = 100;
wp1.z = 7;
Waypoint wp2;
wp2.action = 'S';
wp2.x = 100;
wp2.y = 100;
wp2.z = 6;
std::vector<Waypoint> listbox_items { wp1, wp2 };
static int listbox_item_current = 1;
ImGui::ListBox("listbox::Cavebot", &listbox_item_current, listbox_items);

Of course this is not working, and I'm getting this error:

E0304   no instance of overloaded function "ImGui::ListBox" matches the argument list

How can I display dynamically all my objects attributes in the listbox?


Solution

  • ImGui::ListBox takes a char* as a displayed text, so you could not use a single char. You should re-design your class like this:

    class Waypoint {
    public:
        int x, y, z;
        std::string action;
    };
    

    Then use this function:

    bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
    

    Example:

    bool waypoint_getter(void* data, int index, const char** output)
    {
        Waypoint* waypoints = (Waypoint*)data;
        Waypoint& current_waypoint = waypoints[index];
    
        *output = current_waypoint.action.c_str(); // not very safe
    
        return true;
    }
    
    ImGui::ListBox(
        "listbox::Cavebot", 
        &listbox_item_current, 
        waypoint_getter, 
        listbox_items.data(), 
        listbox_items.size()
    );