Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 702
Ryan Avatar asked Jul 23 '15 13:07

Ryan


People also ask

What does it mean to use Signal?

Signal, like WhatsApp, is a chat app that lets you message and call friends and family using end-to-end encryption, which means your messages are more protected and can't be easily read by anyone, including Signal itself.

Is Signal better than WhatsApp?

Signal is more secure since the app provides end-to-end encryption by default and the company does not keep records of your communications. While messages on WhatsApp are also secure and end-to-end encryption is on by default.

Is Signal owned by Facebook?

But unlike WhatsApp, Signal is not owned by Facebook.

Is Signal a trustworthy app?

“Signal is safe to use, mainly because it provides end-to-end encryption, which means messages are secured before they're sent, and they are decrypted only once they arrive at the intended recipient's device”, explained McAfee VP Antony Demetriades.


1 Answers

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.

like image 168
TheDarkKnight Avatar answered Oct 19 '22 02:10

TheDarkKnight