Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Non-working sliders when iterating through vector #654

Closed
mruegenberg opened this issue May 12, 2016 · 2 comments
Closed

Non-working sliders when iterating through vector #654

mruegenberg opened this issue May 12, 2016 · 2 comments
Labels
label/id and id stack implicit identifiers, pushid(), id stack

Comments

@mruegenberg
Copy link

I've found a pretty weird behavior where I can't influence slider values (I can drag, but the slider always snaps back to the original value).

Basically, the following fails:

std::vector<float> foos;
foos.push_back(0.3);
// ...
for(float s : foos) {
    ImGui::SliderFloat("float x", &s, 0.0f, 1.0f);
}

but this works:

std::vector<float> foos;
foos.push_back(0.3);
// ...
for(float &s : foos) {
    ImGui::SliderFloat("float x", &s, 0.0f, 1.0f);
}

I'm not sure if this is expected behavior and/or can even be reproduced on other systems (I compiled with g++ 6.1.1), but I'd be interested in the reasons for the failure.

In the attachment, there is a full main.cpp (as a txt, because Github only allows those)
main.cpp.txt
which can be dragged into opengl_example to reproduce the issue.

@aytekaman
Copy link

aytekaman commented May 12, 2016

In the first case, you work on copied data so actual values in foo don't change. Second example works since you work with the actual elements in the container.

@ocornut
Copy link
Owner

ocornut commented May 12, 2016

Hello,

What @aytekaman said. The for (float s : foos) is making a copy of your value so you aren't editing the value in your array.

For the second, you need to resolve ID collision somehow as you can't have multiple fields in the same location with the same "float x" identifier. Otherwise all the sliders will react as they are the same one (if you push more than 1 item in your vector you will notice that).

Please read the FAQ entry about usage of ID.

You can do

for (int n = 0; n < foos.size(); n++)
{
   ImGui::PushId(n);  // push a unique id to remove ambiguity
   ImGui::SliderFloat("float x", &foos[n], 0.0f, 1.0f);
   ImGui::PopId();
}

If your values are pointers you can often push the pointer into the id stack.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
label/id and id stack implicit identifiers, pushid(), id stack
Projects
None yet
Development

No branches or pull requests

3 participants