Sending signal from static class method in Qt

后端 未结 4 549
有刺的猬
有刺的猬 2020-12-29 09:08

I am trying to code a static callback function that is called frequently from another static function within the same class. My callback function needs to emit

相关标签:
4条回答
  • 2020-12-29 09:15

    There is an elegant solution. You can emit a signal in a static member function like this:

    emit (instance().newMessage(message));
    
    0 讨论(0)
  • 2020-12-29 09:19

    That is not going to work, because you are creating a new Foo every time you enter that static function, and you do not connect a signal to a slot.

    So, the fix would be to pass the object to that function :

    class Foo
    {
    signals:
        emitFunction(int);
    private:
        static int callback(int val, Foo &foo)
        {
            /* Called multiple times (100+) */
            foo.emitFunction(val);
        }
        void run()
        {
            callback(percentdownloaded, *this);
        }
    };
    

    Another option is to use postEvent, but I wouldn't recommend it.


    Since you can not modify callback's signature, you can do it like this :

    class Foo
    {
    signals:
        emitFunction(int);
    private:
        static int callback(int val)
        {
            /* Called multiple times (100+) */
            theFoo->emitFunction(val);
        }
        static Foo *theFoo;
        void run()
        {
            callback(percentdownloaded, *this);
        }
    };
    

    but you'll have to initialize that static variable somewhere.

    0 讨论(0)
  • 2020-12-29 09:21

    in case someone still finding the solution, here is what I did, it works in my project. 1. make your class to be a singleton 2. in static cb function , load emitFunction from the your singleton class

        static int callback(int val)
       {
       /* Called multiple times (100+) */
       MYClass::getInstance()->emitFunction(val);
       }
    
    0 讨论(0)
  • 2020-12-29 09:26

    You must provide a pointer to the class instance in order to make it work.

    Notice however that in general it is not advised to emit signals from static functions. Static functions can be called without creating an instance of the class, which means that (if you do not provide as argument the sender and use it explicitely), you will not have a "sender" object for the emited signals.

    For these cases as Lol4t0 suggests I also prefer callbacks.

    0 讨论(0)
提交回复
热议问题