Lambda: How to pass object in ?
-
@sonichy said in Lambda: How to pass object in ?:
QTimer::singleShot(100, ui->pushButton, [=]{ ui->pushButton->setDown(false); });
You already capture all variables available in the same scope by value via [=]
If you only want to catch a class member then do:QTimer::singleShot(100, ui->pushButton, [this]{ ui->pushButton->setDown(false); });
Please read https://en.cppreference.com/w/cpp/language/lambda as your question isn't related to Qt (better ask such questions in https://forum.qt.io/category/34/c-gurus)
-
@sonichy said in Lambda: How to pass object in ?:
I want to replace ui->pushButton in the { ... }, not the = in the [... ]
What does "replace" mean here?
If you want to access class member inside the lambda (inside {}) you have to capture "this" in []. This is how lambdas work.
This should work just fine, did you try?QTimer::singleShot(100, ui->pushButton, [this]{ ui->pushButton->setDown(false); });
This can't work because setDown() is not a slot:
QTimer::singleShot(100, ui->pushButton, SLOT(setDown(false));
-
@sonichy "I want to pass "ui->pushButton" through "this"." - "ui" is part of "this", to access it you need "this", so you simply pass "this" to the lambda.
Why don't you simply try what I suggested?!This is invalid code:
QTimer::singleShot(100, ui->pushButton, [this](){ this->setDown(false); });
setDown() is a method of a QPushButton instance. "this" is not a pointer to a QPushButton instance.
To access member variables and methods in a lambda you need to capture "this" as I already explained. So, this is the solution:QTimer::singleShot(100, ui->pushButton, [this](){ ui->pushButton->setDown(false); });