Sending signal from static class method in Qt

后端 未结 4 550
有刺的猬
有刺的猬 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: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.

提交回复
热议问题