Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Lambda: How to pass object in ?



  • If do not use global variable, how to pass ui->pushButton to function of lambda ?

    ui->pushButton->setDown(true);
    QTimer::singleShot(100, ui->pushButton, [=]{ ui->pushButton->setDown(false); });
    

  • Lifetime Qt Champion

    @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)



  • @jsulm I want to replace ui->pushButton in the { ... }, not the = in the [... ]
    Something like

    QTimer::singleShot(100, ui->pushButton, [=]{ sender()->setDown(false); });
    QTimer::singleShot(100, ui->pushButton, SLOT(setDown(false));
    

  • Lifetime Qt Champion

    @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));
    


  • @jsulm I want to pass "ui->pushButton" through "this".

    QTimer::singleShot(100, ui->pushButton, [this]{ this->setDown(false); });


  • Lifetime Qt Champion

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


  • alternatively: QTimer::singleShot(100, ui->pushButton, std::bind(&QPushButton::setDown,ui->pushButton,false));. You don't need a lambda to just forward a call to another method


Log in to reply