How to Use Slots in C++


A slot is an area where you can insert a signal to an object. Slots are usually slightly slower than callbacks, as they require overhead to safely iterate over all connections.

In C++, you can use slots to receive signals. Using a connection object and marshalling parameters, you can connect your signal to a slot. You must be careful to use only those classes that define a signal. If you emit a signal from a class that is not related to the class that defines the slot, the private slot will be invoked in the unrelated class.

When you use a slot to receive a signal, you must be careful to use a different name than you do for your signal. This will prevent your signal from being invoked in the wrong place.

A slot is also used to receive information from other widgets. For example, in QScrollBar, you can connect the valueChanged() signal to the display() slot.

When you call the display() slot, Qt will select the appropriate version of the display() signal. To make sure your signal is invoked in the correct thread, you must define a context object.

Then, when you call the signal, you can connect it to the slot using the QObject::connect() macro. Note that the SLOT() signature must have more arguments than the SIGNAL() signature.

Slots follow normal C++ rules. They are not automatically invoked by other components. However, if they are called directly, they follow the normal rules.