Checkbox functionality

Hi, I am making a GUI system for my engine, and I have access to all the framework. The problem is that the select - unselect functionality does not work:

The following code is in the Checkbox class, and it is called every frame.

if(isClicked()) {
if(selected) {
selected = false;
std::cout << "Selected \n";
}

if(!selected) {
selected = true;
std::cout << "Unselected \n";
}
}


I get the following result when I click the checkbox:

Unselected
Selected
Unselected
Selected....

Here is the graphical results:
The checkbox starts off with the variable "selected = false", so when I first click the checkbox, it works perfectly, then when I need to unselect, it stays selected.
It has gotten really annoying at this point, please help.
Last edited on
You should use a functional UI callback system. How I do it is by using functional and contain a function like this for a toggle button std::function<bool(void)>, and if you need to put in a value or the scope to an overarching class, you can use lambdas or the latter, binding.

Basically your buttons will now only call a function like input(), and then that will lead to the callback being called if the mouse button down collided with the button.

Also note, you absolutely should not be checking input every frame, I am quite confident that most API's will allow you to decouple the logic and input code away from each other and only let input code be called only when the API lets you, and this code should probably be in that input section.

But the actual answer to your question is that you should be doing something like:
1
2
3
4
5
6
7
if(isClicked()) {
  if(!selected)
    std::cout << "Selected \n";
  else
    std::cout << "Unselected \n";
  selected = !selected;
}
Last edited on
Also note, you absolutely should not be checking input every frame

Care to explain why?
graphics run what, 60-80 hz? Its probably sufficient to check every 5th time if you must do polling, but its better to do event driven, I would think, eg "on-click" or "on-changed" style from MFC. Not that these checks are expensive, but stuff adds up and if you had 10 boxes on the UI...

I always did check boxes very light, sort of this way:
on_clicked()
{
checked = !checked;
}

...
if(whateverbox.checked())
{
do something
}


Topic archived. No new replies allowed.