我想调用某个lambda函数A
一次,下一次我想调用lambda函数B
。
例如:
connect(someButton, &QPushButton::clicked, this, [=]()
{
QMessageBox::information(this, "Function A", "This is FIRST Message");
});
然后我想断开这个功能,连接到第二个:
connect(someButton, &QPushButton::clicked, this, [=]()
{
QMessageBox::information(this, "Function B", "This is SECOND Message");
});
预期结果:
Button clicked first time - "This is FIRST Message"
Button clicked second time - "This is SECOND Message"
…
Button clicked 10th time - "This is TENTH Message"
您可以使用具有可变状态的lambda。例如:
[counter = 0]() mutable {
if (counter++ == 0)
; // first time
else
; // afterwards
};
我认为这样的捕获需要C++14。
另一个不使用mutable的例子是放入一个静态变量进行检查。类似的东西
[](){
static bool isFirstTime = true;
if (isFirstTime) {
// first time code
isFirstTime = false;
}
else {
// subsequent times code
}
}
解决方案取决于开发环境的现代化程度:
void CPP14() { // C++14 & up
connect(button, &QPushButton::clicked, this, [first = true]() mutable {
if (first) {
qDebug() << "first call";
first = false;
} else {
qDebug() << "second call";
}
});
}
void CPP11() { // C++11
int first = true;
connect(button, &QPushButton::clicked, this, [first]() mutable {
if (first) {
qDebug() << "first call";
first = false;
} else {
qDebug() << "second call";
}
});
}
// C++98 or Qt 4
class OnClick : public QObject {
Q_OBJECT
public:
bool first;
OnClick(QObject *parent) : QObject(parent), first(true) {}
Q_SLOT void slot() {
if (first) {
qDebug() << "first call";
first = false;
} else {
qDebug() << "second call";
}
}
};
class Class : public QWidget {
QPushButton *button;
void CPP98() {
connect(button, SIGNAL(clicked(bool)), new OnClick(this), SLOT(slot()));
}
};