Joe
Joe

Reputation: 9

QT C++ How to call lambda one?

I want to call some lambda function A once, and all the next time I want to call the lambda function B.

For example:

connect(someButton, &QPushButton::clicked, this, [=]()
{
    QMessageBox::information(this, "Function A", "This is FIRST Message");
});

Then I want to disconnect from this function and connect to the second one:

connect(someButton, &QPushButton::clicked, this, [=]()
{
    QMessageBox::information(this, "Function B", "This is SECOND Message");
});

Expected result:

Button clicked first time - "This is FIRST Message"
Button clicked second time - "This is SECOND Message"
…
Button clicked 10th time - "This is TENTH Message"

Upvotes: 0

Views: 430

Answers (3)

The solutions depend on how modern is your development environment:

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()));
   }
};

Upvotes: 0

Stanton
Stanton

Reputation: 1076

Another example without using mutable would be to put a static variable to check. Something like

[](){
    static bool isFirstTime = true;
    if (isFirstTime) {
        // first time code
        isFirstTime = false;
    }
    else {
        // subsequent times code
    }
}

Upvotes: 0

lubgr
lubgr

Reputation: 38287

You can use a lambda with mutable state. As an example:

[counter = 0]() mutable {
   if (counter++ == 0)
      ; // first time
   else
      ; // afterwards
};

I think C++14 is required for such a capture.

Upvotes: 2

Related Questions