Skip to content

AddCallback

Otavio edited this page Jul 21, 2021 · 11 revisions

CWidgets::AddCallback

What it does:

This function adds a function callback for the widget to trigger. In other words, it adds a function to the widget to call.

Parameters:

This function takes a std::function<void()> argument. So in theory you can only add callbacks with no arguments.

NOTE: If you want to add a function with arguments, take a look at std::bind.

Widgets:

List of widgets that are using this function and how the callbacks are triggered:

  • Label - It will trigger the callback when you click on a label.
  • Button - It will trigger the callback when you click on the button.
  • Container (Window) - It will trigger the callback when it's active (toggled)
  • CheckBox - It will trigger the callback when your checkbox state is set to true (checked)
  • MultiBox - It will trigger the callback when you select something on the dropdown list
  • ListBox - It will trigger the callback when you select something on the list

Setting up a Callback

Here's how you can add a callback to one of these widgets. First we'll need a function to call.

void callback_example1()
{
  // this function will print a colored text in the console
  ICVar->ConsoleColorPrintf(255, 255, 0, 255, "callback called!\n");
}

// or

void callback_example2(std::string text)
{
  // this function will print a colored text in the console
  ICVar->ConsoleColorPrintf(255, 255, 0, 255, text.c_str());
}

Now that we have a simple callback we can add it into our widget. I'll be using a Button as an example.

buildrPattern.Widget(Button).Title("Click me!").Font("Tahoma", 12, true).Position(30, 30).Callback(callback_example1).SpawnIn(Container);

// or

buildrPattern.Widget(Button).Title("Click me!").Font("Tahoma", 12, true).Position(30, 30).Callback(std::bind(callback_example2, "callback called!\n")).SpawnIn(Container);

NOTE: There's an extra function added into the pattern: Callback. This function takes an instance of the function that we want to call. So as you saw above: It's just the function name without the ().

After adding this into your menu, whenever you click on the button it will call this function.

RESULT: callback called!

You can use your creativity to do whatever you want, call a function to save a configuration, close your application, etc.


What's next?

Next you will learn about the AddEntry function.