Search code examples
qtmacrossignalsslot

SIGNAL & SLOT macros in Qt : what do they do?


I'm a beginner in Qt and trying to understand the SIGNAL and SLOT macros. When I'm learning to use the connect method to bind the signal and slot, I found the tutorials on Qt's official reference page uses:

connect(obj1, SIGNAL(signal(int)), obj2, SLOT(slot()))

However, this also works very well:

connect(obj1, &Obj1::signal, obj2, &Obj2::slot)

So what exactly do the macros SIGNAL and SLOT do? Do they just look for the signal in the class the object belongs to and return the address of it?

Then why do most programmers use these macros instead of using &Obj1::signal since the latter appears to be simpler and you don't need to change the code if the parameters of the signal function change?


Solution

  • The use of the SIGNAL and SLOT macros used to be the only way to make connections, before Qt 5. The connection is made at runtime and require signal and slots to be marked in the header. For example:

    Class MyClass : public QObject
    {
        Q_OBJECT
        signals:
            void Signal();
    
        slots:
            void ASlotFunction();
    };
    

    To avoid repetition, the way in which it works is described in the QT 4 documentation.

    The signal and slot mechanism is part of the C++ extensions that are provided by Qt and make use of the Meta Object Compiler (moc).

    This explains why signals and slots use the moc.

    The second connect method is much improved as the functions specified can be checked at the time of compilation, not runtime. In addition, by using the address of a function, you can refer to any class function, not just those in the section marked slots:

    The documentation was updated for Qt 5.

    In addition, there's a good blog post about the Qt 4 connect workings here and Qt 5 here.