Levi Levi - 28 days ago 10
C++ Question

Wt connect function, passing a parameter to a function which is a connect function argument

The following code snippet uses Wt/C++ connect which takes two arguments.
How to pass an argument to &mode::func.

button = new WPushButton("func 1", buttons);
stuff()->addWidget(button);
button->clicked().connect(this, &mode::func);


In other words, how to make &mode::func(number). Look the desired code below.

int number = 5;
button = new WPushButton("func 1", buttons);
stuff()->addWidget(button);
button->clicked().connect(this, &mode::func(number));

Answer Source

Because Wt 4 will be released soon, I'll mention how it can be done in Wt 4 too.

For Wt 3:

If you connect a function like that, then mode::func will be called with the WMouseEvent of the clicked signal if it takes an argument. You could use boost::bind instead:

int number = 5;
button = new WPushButton("func 1");
stuff()->addWidget(button);
button->clicked().connect(boost::bind(&mode::func, this, number));

This will still automatically disconnect the slot if this is deleted, just like your original code. If you use std::bind (or a lambda) instead, it won't automatically disconnect the slot.

I removed the buttons argument from your original code, because it sets buttons as the parent, but subsequently moves it to stuff() using addWidget, making that the parent.

For Wt 4:

In Wt 4, you will have to use std::bind or a lambda function. You could do it like this:

int number = 5;
button = stuff()->addWidget(std::make_unique<WPushButton>("func 1"));
button->clicked().connect(bindSafe([this,number]{
  func(number);
}));

bindSafe makes sure that the lambda is not called after this is deleted.

You can omit bindSafe if you don't want to guard against deletion of this. In many practical cases button is deleted before this, making bindSafe unnecessary.