Back to TILs

C++ fltk — 5 — libsigcplusplus

Date: 2023-03-20Last modified: 2024-11-02

Table of contents

#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Window.H>
#include <FL/fl_ask.H>
#include <sigc++/sigc++.h>

#include <iostream>

static sigc::signal<void()> SignalClickMe;
static sigc::signal<void()> SignalIncrement;

class WindowTest : public Fl_Window {
  int counter = 0;
  bool button1_clicked = false;
  Fl_Button* button1;
  Fl_Button* button2;
  Fl_Box* label;

  void onClickMe() {
    std::cout << "onClickMe()" << std::endl;
    if (button1_clicked) {
      fl_alert("Stop it, you've clicked me already!");
    } else {
      button1->label("Thank you!");
      button1_clicked = true;
    }
  }

 public:
  WindowTest() : Fl_Window(300, 300, 300, 200, "Lambda & Signals") {
    button1 = new Fl_Button(5, 5, 80, 25, "Click me");
    button2 = new Fl_Button(5, 70, 80, 25, "Increment");
    label = new Fl_Box(5, 100, 80, 25, "Counter: 0");

    button1->callback([]([[maybe_unused]] Fl_Widget* w,
                         [[maybe_unused]] void* u) { SignalClickMe.emit(); });

    button2->callback([]([[maybe_unused]] Fl_Widget* w,
                         [[maybe_unused]] void* u) { SignalIncrement.emit(); });

    SignalClickMe.connect(sigc::mem_fun(*this, &WindowTest::onClickMe));

    SignalIncrement.connect([this] {
      char text[50];
      sprintf(text, "Counter: %d", ++counter);
      label->copy_label(text);
      std::cout << "Lamda incremment called " << counter << std::endl;
    });
  }
};

int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) {
  WindowTest* window = new WindowTest();
  window->show(0, NULL);
  return Fl::run();
}

Possible output

onClickMe()
onClickMe()
onClickMe()
Lamda incremment called 1
Lamda incremment called 2
Lamda incremment called 3
onClickMe()

References