PDA

View Full Version : How to emit a signal from a static function



buster
23rd March 2020, 01:38
I have been trying to emit a signal from a static function, but get an error message:
error: cannot call member function ‘void MyClass::myStaticFunction()’ without object
emit connectionChanged();
^
The function myStaticFunction() is declared as static because it is a callback function from some processing interface. I have verified that when I do not try to emit a signal myStaticFunction() is duly called. MyClass is derived from QObject:

class MyClass : public QObject
{
Q_OBJECT

I presume there must be a (simple?) solution to this?

d_stranz
23rd March 2020, 04:34
Signals must be declared using the "signals:" syntax in your class declaration. You didn't show anything really to tell us how you declared it.

Signals must be emitted through an instance of the class that declares them. So I do not think there is a way that you can invoke "emit' via a static method. The corresponding slot must be able to resolve the instance that sent the signal (via QObject::sender()) and with a static method, there is no sender.

Maybe if you showed a bit more context about what you are trying to do, we could provide some better advice. There are probably tricks you can use to map a static callback onto a member function of a class instance.

One way I can think of is to make your callback function a member of a struct that also contains a static member that points to a QObject class instance. Signals are just ordinary C++ methods, and "emit" pretty much maps to "this->", so in your static callback method in the struct you could simulate the emit in this way:



struct CallbackForwarder
{
static void myCallback()
{
if ( myInstance )
myInstance->doCallback();
}

static MyClass * myInstance = nullptr;
}


and you would pass &CallbackForwarded:: myCallback as the address of your callback function to your processing interface. Depending on that interface, you might also be able to define the callback as a functor (operator()()) or as a lambda.