Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a slot is connected to a given signal

Tags:

c++

signals

qt

I'm interested to know if there is some way that I can determine that there is a connection to a given signal that I've defined in a class. It's basically a signal to process data, and I don't care what it's connected to, but I'd like to include a sanity check that I'm not sending data into the void where it will never be seen. I've checked out Determine signals connected to a given slot in Qt, but it's kind of the opposite problem.

like image 683
Nicolas Holthaus Avatar asked Jan 12 '15 18:01

Nicolas Holthaus


People also ask

What is signal slot connection?

A slot is called when a signal connected to it is emitted. Slots are normal C++ functions and can be called normally; their only special feature is that signals can be connected to them. Since slots are normal member functions, they follow the normal C++ rules when called directly.

In what order will the slots be executed if they are connected to one signal?

If several slots are connected to one signal, the slots will be executed one after the other, in the order they have been connected, when the signal is emitted. Signals are automatically generated by the moc and must not be implemented in the . cpp file.


1 Answers

There is QObject::isSignalConnected() for exactly that usecase - avoiding unnecessary work to prepare a signal emission when no one is listening. Its API docs even come with a nice example.

Example:

static const QMetaMethod valueChangedSignal = QMetaMethod::fromSignal(&MyObject::valueChanged);
if (isSignalConnected(valueChangedSignal)) {
    QByteArray data;
    data = get_the_value();       // expensive operation
    emit valueChanged(data);
}
like image 154
Thomas McGuire Avatar answered Oct 05 '22 11:10

Thomas McGuire