I want to be able to call multiple functions/ methods when a timer timeouts, without creating a new slot method that calls the desired methods (see code).
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);
}
Is there a better solution?
First, you should use Qt's new signal and slot syntax if you can.
I can think of 2 ways I would solve this problem:
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);
}
Just make 2 timers every time. The overhead is probably not enough to actually care about.