Reputation: 510
I've just started working with Qt on Windows and read about moveToThread() function. Would it be ok if I write like this:
class Worker : public QObject
{
Q_OBJECT
private:
QThread* thread;
public:
void GoToThread() {
thread = new QThread();
this->moveToThread(thread);
}
void DoWork() {
//long work
}
};
Worker* w = new Worker();
w->GoToThread();
w->DoWork();
And what exactly would this code do? Would it put itself to the thread? Would I be able to call DoWork() outside?
Upvotes: 0
Views: 3278
Reputation: 7034
That will move the QObject to the new thread and on top of what Michael Burr already said you should take a look in the documentation here because you miss at least a connect thread finished to deleteLater for your QObject (and this will cause a memory leak)
Upvotes: 3
Reputation: 340168
In the example you gave, DoWork()
would execute on the caller's thread.
If you want DoWork()
to be done on the Worker
object's thread, you should have DoWork()
be a slot that can be invoked either by emitting a signal that it has been connected to or by calling QMetaObject::invokeMethod()
to 'call' it.
Basically, moving a Q_OBJECT
to another thread makes that Q_OBJECT
use an event queue associated with that thread, so any events delivered to that object via the event queue will be handled on that thread.
Upvotes: 3