1

Typically Qt signals are triggered on a specific instance of a QObject.

Is there a way to trigger it on all instances of a specific class via, perhaps, MetaObjects?

Or the only way is to maintain your own static list of all instances, perhaps by using constructors and destructors, and then just Q_FOREACH it?

qdot
  • 6,195
  • 5
  • 44
  • 95

2 Answers2

3

Signals cannot be emitted outside of the class that defines them (or derives from the class that defines them) without invoking it through the QMetaObject system:

QMetaObject::invokeMethod( myObj, "mySignal",
                           Q_ARG( QString, "str" ),
                           Q_ARG( int, 42 ) );

However there doesn't appear to be an API method of getting all objects of all particular type to emit, the nearest I could find is:

for ( QWidget* widget : QApplication::allWidgets() ) {
    if ( dynamic_cast< myType* >( widget ) ) {
        QMetaObject::invokeMethod( widget, "mySignal",
                                   Q_ARG( QString, "str" ),
                                   Q_ARG( int, 42 ) );
    }
}

But obviously this only works for QWidget derived types, there doesn't appear to be a QObject equivalent.

cmannett85
  • 21,725
  • 8
  • 76
  • 119
3

How about creating a singleton behind the scenes, and connecting all your instances to a signal from that singleton (signal-to-signal connection)? When you want all your instances to emit the signal, just make the singleton emit it, and all instances will forward it.

David Faure
  • 1,836
  • 15
  • 19
  • It's actually quite a good idea - a lot better than my concept of a global static member variable. – qdot Oct 13 '12 at 12:02
  • I"ve worked with the sigleton object as broadcaster pattern multiple times. But this will then introduce another class and its meta object. Way more efficient is to use a slightly easier approach: use the very first object of the class as the broadcaster to all other instances. Have a static pointer to a class object, initialized as nullptr. If the constructor finds it in that state, this is the first. If not, connect to its broadcasting signal and your are done. Emitting is done by calling a mehtod through this singleton-like structure. – Patrick Z Mar 15 '23 at 09:24
  • @PatrickZ interesting idea. Obviously not applicable if the first instance can get deleted at some point, though ;-) – David Faure Mar 17 '23 at 16:43
  • That is correct. Normally one should be aware of the situation, in that case, use a non-public, non acessible sacrificial instance (if it is not that big). Since its Qt, provide it a parent to get properly cleaned up afterwards. – Patrick Z Mar 20 '23 at 13:34