问题描述
我正在尝试编写一个静态回调函数,该函数经常从同一类中的另一个静态函数调用.我的回调函数需要 emit
一个信号,但由于某种原因它根本无法这样做.我把它放在调试器下,slot
永远不会被调用.但是,当我将用于 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中的静态类方法发送信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!