c++qtqmake

How to use a lambda function with QObject::connect()? Error: no matching function for call to connect()


I am trying to pass a parameter (a reference to QMainWindow) to a slot callback method using a lambda function. Here is a minimal example:

#include "Start.hpp"

int main(int argc, char *argv[ ])
{
    auto start = Start{argc, argv};
    return start.start();
}

int Start::start() {
    QApplication app(argc_, argv_);
    QMainWindow window;
    window.setWindowTitle("MainWindow");
    QPushButton *button = new QPushButton("Start", &window);
    QObject::connect(
        button,
        SIGNAL(released()),
        this,
        [this, &window](QMainWindow&){this->displayWidget(window);}
    );
    window.setCentralWidget(button);
    window.resize(400, 300);
    window.show();
    return app.exec();
}

void Start::displayWidget(QMainWidow &window)
{
    QMessageBox msgBox {&window};
    msgBox.setText("The button was clicked.");
    msgBox.exec();
}

where the header file Start.hpp is

#ifndef START_HPP
#define START_HPP
#include <QAction>
#include <QApplication>
#include <QPushButton>
#include <QDebug>
#include <QMainWindow>
#include <QObject>

class Start : public QObject {
    Q_OBJECT

public:
    Start(int argc, char* argv[]) : argc_{argc}, argv_{argv} {}
    int start();

private:
    int argc_;
    char **argv_;
private slots:
    void displayWidget(QMainWindow &window);
};
#endif

When compiling this program with qmake, I get the following error message:

Start.cpp: In member function ‘int Start::start()’:
Start.cpp:14:21: error: no matching function for call to ‘Start::connect(QPushButton*&, const char*, Start*, Start::start()::<lambda(QMainWindow&)>)’
   14 |     QObject::connect(

Solution

  • You can't mix old (obsolete with C++ classes) and "new" (since Qt 5 over a decade ago) connect syntax. Connecting to a lambda only works with new syntax.

    Also, released() signal has no parameters, so a lambda can't have them either.

    This Should be valid:

    QObject::connect(
        button,
        &QPushButton::released,
        this,
        [this, &window](){this->displayWidget(window);}
    );