Var in Lambda pass out ?



  • error: assignment of read-only variable ‘bv’ : bv = v;

    void MainWindow::on_action_brightness_triggered()
    {
        int bv = 0;
        QDialog *dialog = new QDialog;
        dialog->setWindowTitle("Brightness");
        dialog->setFixedSize(400,200);
        QSlider *slider = new QSlider(Qt::Horizontal);
        slider->setRange(-50, 50);
        slider->setTickPosition(QSlider::TicksBelow);
        connect(slider, &QSlider::valueChanged, [=](int v){
            bv = v;
            imageWidget->adjustBrightness(v, false);
        });
        QVBoxLayout *vbox = new QVBoxLayout;
        vbox->addWidget(slider);
        QPushButton *pushButton_confirm = new QPushButton("Confirm");
        QPushButton *pushButton_cancel = new QPushButton("Cancel");
        QHBoxLayout *hbox = new QHBoxLayout;
        hbox->addStretch();
        hbox->addWidget(pushButton_confirm);
        hbox->addWidget(pushButton_cancel);
        hbox->addStretch();
        vbox->addLayout(hbox);
        dialog->setLayout(vbox);
        connect(pushButton_confirm, SIGNAL(clicked()), dialog, SLOT(accept()));
        connect(pushButton_cancel, SIGNAL(clicked()), dialog, SLOT(reject()));
        if(dialog->exec() == QDialog::Accepted){
            imageWidget->adjustBrightness(bv, true);
        }
    }
    

  • Moderators

    bv goes out of scope when on_action_brightness_triggered() method ends (}). Your lambda is called afterwards, when the variable does not exist anymore.

    Make bv a class member, not local variable and it won't show an error.



  • My net friend show me the simplest way : change lambda [=] to [&].
    It works, but I do not know why.


  • Moderators

    @sierdzio said in Var in Lambda pass out ?:

    bv goes out of scope when on_action_brightness_triggered() method ends (}). Your lambda is called afterwards, when the variable does not exist anymore.

    In this case, dialog->exec() blocks and runs a new event loop so bv technically remains in scope until the dialog and the connection gets destroyed.

    It's a fragile design, however.

    @sonichy said in Var in Lambda pass out ?:

    My net friend show me the simplest way : change lambda [=] to [&].
    It works, but I do not know why.

    • [=] gives your lambda a copy of bv.
    • [&] gives your lambda a reference to bv.

    See the answer of https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.