5

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?

lnk
  • 593
  • 2
  • 11
  • 27
  • 1
    Make sure your class inherits from QObject and has the Q_OBJECT macro defined: http://www.bogotobogo.com/Qt/Qt5_Q_OBJECT_Macro_Meta_Object.php – TheDarkKnight Sep 23 '14 at 14:10
  • 1
    `connect` is a static method of QObject. You can write `QObject::connect(...` – borisbn Sep 23 '14 at 14:13

1 Answers1

2

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.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
  • I have got other buttons in my program. Ordinary connect(&, SIGNAL(), &, SLOT()) works great in the program. Now I have cheked that Qt 5 new syntax also work without error. However when I am trying to use connect with lambda compiler gives an error. I have got a lot of "simple" buttons in my program, so I dont want to create a bunch of functions with one or two line in it. – lnk Sep 23 '14 at 15:18
  • Have you set your .pro file to use C++ 11 ? http://stackoverflow.com/questions/19398438/c-qt-how-to-add-std-c11-to-the-makefile-which-is-generated-by-qmake/19398489#19398489 – TheDarkKnight Sep 23 '14 at 15:25
  • 1
    @ Merlin069 I have put CONFIG+=C++11 line in .pro file. Now it works! I thought that C++11 is used automatically in QT5 – lnk Sep 23 '14 at 16:21