【问题标题】:Passing A Parameter Along with a Function Pointer将参数与函数指针一起传递
【发布时间】:2014-03-09 02:55:55
【问题描述】:

我在一个项目中使用Wt C++ 库。我正在尝试使用connect(...) 功能将插槽连接到按钮按下。 connect(...) 函数的文档可以在 here 找到。

基本上,每次在一组单选按钮中检测到更改时,都会调用作为指向connect(...) 函数的指针传递的函数。

下面是简短的sn-p代码:

...

_group = new Wt::WButtonGroup(this);
Wt::WRadioButton *button;

button = new Wt::WRadioButton("Radio Button 0", this);
_group->addButton(button, 0);

_group->setSelectedButtonIndex(0); // Select the first button by default.

_group->checkedChanged().connect(this, (&MyWidget::RadioButtonToggle)); //Need to pass parameter here  

...

我需要将selection 参数传递给函数RadioButtonToggle(Wt::WRadioButton *selection),以便我可以在函数体中使用它,如下所示:

void CycleTimesWidget::RadioButtonToggle(Wt::WRadioButton *selection)
{
    switch (_group->id(selection))
    {
        case 0:
    {
            //Do something...
            break;
        }
    }
}

如何将参数与函数指针一起传递?

【问题讨论】:

标签: c++ wt


【解决方案1】:

您可以使用Wt:WSignalMapper,可以在here 找到文档。使用Wt:WSignalMapper,您可以将多个发件人连接到一个插槽。在您的情况下,多个发件人是不同的Wt:WRadioButton

Wt::WSignalMapper<Wt:WRadioButton *> * mapper = new Wt::WSignalMapper<
        Wt::WRadioButton *>(this);
mapper->mapped().connect(this, &MyWidget::RadioButtonToggle);

// for all radio buttons
mapper->mapConnect(button->changed(), button);
...

然后您可以使用上面在您的问题中所写的函数RadioButtonToggle

更新:

正如 cmets 中所指出的,Wt:WSignalMapper 已过时。如果您使用 C++ 11 或更高版本,您现在应该使用 boost::bind()std::bind()。那么代码就变成了:

// for all radio buttons
button->changed().connect(boost::bind(this, &MyWidget::RadioButtonToggle, button));

【讨论】:

  • 这太棒了!我在文档中没有看到这一点。非常感谢。接受的答案。
  • WSignalmapper 实际上已经过时了。现在更短、更简单且首选的方法是使用 boost::bind(),请参阅常见问题解答 redmine.webtoolkit.eu/projects/wt/wiki/…
猜你喜欢
  • 2016-11-07
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
  • 2019-09-16
  • 2018-08-25
  • 2012-05-03
  • 2012-11-26
相关资源
最近更新 更多