QTimer过期时如何调用多个函数



我希望能够在计时器超时时调用多个函数/方法,而无需创建一个新的slot方法来调用所需的方法(请参阅代码(。

int foo;
int bar;
// …
private slots:
inline void foo_func() { /*…*/ }
inline void bar_func() { /*…*/ }
inline void combination_of_multiple_func()
{
foo_func();
bar_func();
}
// …

// somewhere in a method:
if (foo == bar)
{
// Schedule … every foo or bar milliseconds
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(combination_of_multiple_func()));
timer->start(foo);
}
else
{
// Schedule … every foo milliseconds
QTimer *fooTimer = new QTimer(this);
connect(fooTimer, SIGNAL(timeout()), this, SLOT(foo_func()));
fooTimer->start(foo);
// Schedule … every bar milliseconds
QTimer *barTimer = new QTimer(this);
connect(barTimer, SIGNAL(timeout()), this, SLOT(bar_func()));
barTimer->start(bar);
}

有更好的解决方案吗?

首先,如果可以的话,您应该使用Qt的新信号和插槽语法。

我可以想出两种方法来解决这个问题:

使用lambda

if (foo == bar)
{
// Schedule … every foo or bar milliseconds
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, [] { foo_func(); bar_func(); } );
timer->start(foo);
}

忽略它

每次只需制作2个定时器。开销可能不足以真正关心。

我的方法是根据需要建立尽可能多的连接,例如:

connect(timer, SIGNAL(timeout()), this, SLOT(combination_of_multiple_func()));

将信号连接到两个插槽:

connect(timer, &QTimer::timeout, this, &WhateverThisIs::foo_func);
connect(timer, &QTimer::timeout, this, &WhateverThisIs::bar_func);

最新更新