PDA

View Full Version : How to start a QTimer in this situation?



iaapmm
28th September 2020, 04:45
class Foo {
private:
QTimer *timer = nullptr;

public:
void Foo (QTimer *timer) : timer(timer) { }

void bar () {
this->timer->start();
}
};

...

QTimer *timer = new QTimer();
Foo *foo = new foo(timer);

obj.func(foo);
timer->connect(timer, &QTimer::timeout, [] {
// do something
});


The program runs in the following order:
1. a third party library creates a new thread.
2. foo object is registered in the library through its obj::func() method.
3. the library calls foo::bar() method.

But after that, the program doesn't work with error message
QObject::startTimer: Timers cannot be started from another thread.

Could you give me some advice if you have a good idea? Thanks.

ChrisW67
28th September 2020, 08:46
Try this...
Give the Foo class a timeout() signal.
Create the QTimer object inside Foo (pass in a period etc.): hopefully you end up with the timer in the same thread as the Foo object.
Connect the timer's timeout() signal to Foo's timeout() signal. This will cause your foo object to emit timeout() when the internal timer emits timeout().