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.
Asked
Active
Viewed 6,702 times
1 Answers
12
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);
}

Nicolas Holthaus
- 7,763
- 4
- 42
- 97

Thomas McGuire
- 5,308
- 26
- 45
-
1can't believe I missed that. – Nicolas Holthaus Jan 12 '15 at 18:23
-
1This did not work for me when an `QObject` was destroyed, while `receivers(SIGNAL(finished())` did work – Boy Dec 06 '17 at 07:01
-
Qt 5.15.0 QObject::isSignalConnected always returns false? – Ed of the Mountain Jul 01 '20 at 16:56