在Qt中从静态类方法发送信号 [英] Sending signal from static class method in Qt

查看:6934
本文介绍了在Qt中从静态类方法发送信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个静态回调函数,该函数从同一类中的另一个静态函数频繁调用。我的回调函数需要 emit 一个信号,但由于某种原因,它只是没有这样做。我把它放在一个调试器和插槽从来没有被调用。然而,当我放置代码我用来 emit 在非静态函数中的数据,它的工作原理。有没有原因,我不能从静态函数发出信号?我尝试声明一个类的新实例,并调用emit函数,但没有运气。

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 a signal but for some reason it simply fails to do so. I have put it under a debugger and the slot never gets called. However when I place the code I used to emit the data in a non-static function it works. Is there a reason I cannot emit a signal from a static function? I have tried declaring a new instance of the class and calling the emit function but with no luck.

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

我已经发布了一些基本的代码,演示了我试图做什么。我将根据请求过帐全部代码。

I have posted some basic code that demonstrates what I am attempting to do. I will post full code upon request.

编辑:我发布完整的代码,因为这是一个奇怪的情况。 http://pastebin.com/6J2D2hnM

I am posting the full code since this is kind of an odd scenario. http://pastebin.com/6J2D2hnM

推荐答案

这不会工作,因为你创建一个新的Foo每次你输入静态函数,并且你不连接到一个插槽的信号。

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);
    }
};

另一个选择是使用 postEvent ,但我不推荐。

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.

这篇关于在Qt中从静态类方法发送信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆