Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connect QPushButton via lambda

Tags:

c++11

lambda

qt

I am trying to connect QPushButton to lambda expression:

      QPushButton* loadTextFileButton = new QPushButton("load");
      connect(loadTextFileButton, &QPushButton::clicked, [](){
         qDebug()<<"clicked";
      });

Compiler gives me an errors like: No matching function to call "MyClass::connect(..."

What I am doing wrong?

like image 987
lnk Avatar asked Nov 01 '22 16:11

lnk


1 Answers

The connect function, which is part of Qt's signal and slots mechanism is Qt's extension to C++.

The connect function is actually a static function of QObject, so you can use it from anywhere, by simply including QObject: -

#include <QObject>
...
QObject::connect(itemPtr1, SIGNAL(someFunction()), itemPtr2, SLOT(someOtherFunction());

The objects itemPtr1 and itemPtr2 are pointers to instances of classes that are derived from QObject and support signals and slots.

In order for a class to use the signal and slot mechanism, it must inherit from QObject and declare the Q_OBJECT macro:-

class MyClass : public QObject
{
     Q_OBJECT // the Q_OBJECT macro, which must be present for signals and slots

     public:
          MyClass(QObject* parent);

     signals:

     public slots:

     private:
           void StandardFunction();
};

As this class inherits QObject, it now has direct access to the connect function, allowing calling connect directly:-

 QPushButton* loadTextFileButton = new QPushButton("load");
 connect(loadTextFileButton, &QPushButton::clicked, []()
 {
     qDebug()<<"clicked";
 });

Finally, Qt 5 introduced a new syntax for signals and slots: -

connect(loadTextFileButton, &QPushButton::clicked, this, &MyClass::StandardFunction);

You may have noticed that the advantage here is that the signal can be connected to a function that is not declared as a slot. In addition, using this syntax provides compile time error checking.

like image 149
TheDarkKnight Avatar answered Nov 09 '22 06:11

TheDarkKnight