Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt connect doesn't recognize with lambda expression

Tags:

c++

lambda

qt

slot

I'm designed a QTableWidget with QPushButton, I would like to connect these buttons with a slot to hide some rows.

I'm using a lambda expression to pass a number of a row. But the compiler doesn't recognized this expression :

connect(this->ui->tableWidget->cellWidget(i,0),&QPushButton::clicked,[this,i]{hideRows(i);});

I have this error:

error: no matching function for call to 'SoftwareUdpater::MainWidget::connect(QWidget*, void (QAbstractButton::*)(bool), SoftwareUdpater::MainWidget::displayTable()::<lambda(int)>)'
  • The function hideRows(int) is declared as a function. And, as a slot, it doesn't work,
  • CONFIG += c++11 is added in pro file,
  • My class MainWidget inherits from QWidget,
  • Q_OBJECT is added in the header.

So I don't udnerstand why connect() is not recognized by Qt 5.9.1 MinGw 32bit.

Edit: [this,i]() instead of [this](const int i) for the lambda expression

like image 656
Liscare Avatar asked Feb 25 '26 08:02

Liscare


2 Answers

Your connection is wrong. You can't connect a function that doesn't take parameters (clicked()) with a function that takes parameters (your lambda). To verify that this is the case, just do this:

connect(this->ui->tableWidget->cellWidget(i,0),&QPushButton::clicked,[this](){});

And see that it will compile. You have to make your design in such a way that signals and slots are compatible.

Also avoid using lambdas in signals and slots. Read the caveats here.

like image 121
The Quantum Physicist Avatar answered Feb 27 '26 21:02

The Quantum Physicist


I was reading your comments on the accepted answer and noticed the root of the problem: This error is being thrown because the effective type of the object — as supplied to QObject::connect; i.e QWidget in your case — does not define the referenced signal QPushButton::clicked.

What likely happened is that the QPushButton pointer was cast into a QWidget and then that pointer was given to connect instead of the original which defines the signal.

Cast the pointer back to a QPushButton * and the error should go away.

like image 41
Tenders McChiken Avatar answered Feb 27 '26 20:02

Tenders McChiken