qt信号槽与c++的lambda表达式

有时候每个槽函数都定义一下非常的麻烦,这时我们就会用到lambda表达式,如:

QAction* actStart = new QAction(tr("start"), this);
connect(actStart, QOverload<bool>::of(&QAction::triggered), [](bool flag){// do something});

但是我们往往需要获取发出者是谁,如:

QAction* actStart = new QAction(tr("start"), this);
connect(actStart, QOverload<bool>::of(&QAction::triggered), [this](bool flag){
  auto act = qobject_cast<QAction*>(sender()); // 获取信号发出对象
  // do something
});

这时就会发现有时通过sender()得到的是nullptr,为什么说是有时呢,同样的写法我在另一个地方就成功了...(待查)
于是我们改用直接捕获信号发送者的方式,如:

QAction* actStart = new QAction(tr("start"), this);
connect(actStart, QOverload<bool>::of(&QAction::triggered), [this, actStart](bool flag){
  actStart->setText("got it!");
  // do something
});

成功捕获到了actStart!这种情况我通常在函数体内new一个非成员变量时使用

参考:Qt Slots and C++11 lambda

posted @ 2022-04-07 11:38  miyanyan  阅读(360)  评论(0)    收藏  举报