7

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.

Community
  • 1
  • 1
Nicolas Holthaus
  • 7,763
  • 4
  • 42
  • 97

1 Answers1

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