I understand the technology of signals and slots. I can connect a class A signal to a class B slot, and I can connect a class A signal to a function. What is the fundamental difference between such implementations?
1 answer
Not with anything. Slots and functions (methods) are the same. For c ++ 11, you can connect signals with lambdas or with functions directly, bypassing the declaration of slots and using the macro SLOT .
Upd: For the slots, some meta information is generated - the name and hint for the slot call. This is where the difference ends and thanks to the moc programmer, this difference will not be visible :)
I will give an example of connecting a signal to the slot, function and method (works for C ++ 11 and Qt5):
This describes the most common header file:
#include <QMainWindow> #include <QPushButton> #include <QDebug> class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); void doooooo(); public: QPushButton button; public slots: void foooooo(); void foooooo2(); }; And the most interesting will be in cpp. There I connect the signal to the slots, method and function:
#include "mainwindow.h" void goooooo() { qDebug() << "goooooo"; } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setCentralWidget(&button); // Новая семантика коннектов: connect(&button, &QPushButton::clicked, this, &doooooo); connect(&button, &QPushButton::clicked, this, &foooooo); connect(&button, &QPushButton::clicked, this, &goooooo); connect(&button, &QPushButton::clicked, this, [] { qDebug() << "lambda"; }); // Старая: connect(&button, SIGNAL(clicked(bool)), this, SLOT(foooooo2())); // Слоты это функции, поэтому можно вручную вызывать их foooooo(); foooooo2(); qDebug() << ""; } void MainWindow::doooooo() { qDebug() << "doooooo"; } void MainWindow::foooooo() { qDebug() << "foooooo"; } void MainWindow::foooooo2() { qDebug() << "foooooo2"; } More information on new connect syntax can be found here.
And on lambda here
- Isn't the meta-information generated using
mocfor the methods declared in theslotssection? - maestro - no, it is not generated, because there are no methods :). no methods - no meta information. - KoVadim