I have done something like this:
//in the mainwindow's constructor
QThread *thr = new QThread;
soundWorker * work = new soundWorker;
connect(this,SIGNAL(playsound()),work,SLOT(process()));
work->moveToThread(thr);
thr->start();
Shall I delete thr and work at the deconstructor of mainwindow?
You can use the default Qt way of managing memory by assigning a parent to the QThread
, i.e. do this:
QThread *thr = new QThread(this);//the mainwindow's is now the thread parent
In Qt, parents are responsible for managing the memory of their children. Thus, the QThread
will be automatically deleted when needed.
Then, for your soundWorker
, you have a few different solutions. If its lifetime is the same as your mainwindow
, as you hint when you ask if you should delete it in the destructor of the mainwindow
, you could simply make it a non-pointer member, and its storage duration would then become automatically handled.
The parent thing is specific to Qt though. In general, when you deal with memory yourself, you should resort to wrappers (such as smart pointers) that enables RAII.
Further reading: Qt Trees and ownership model
You can use the QThread::finished()
signal in order detect the moment you wish to release the QThread
pointer. Same thing could be done with QObject
pointers which were moved to the new thread.
Considering that the moment of closing the main window is the moment of closing the whole application and considering that you don't need to further do processing after the application was closed, you can pass the main window pointer as a parent to the QThread
by either passing it to the constructor or using QObject::setParent
.
Releasing the resources acquired inside the thread handled by QThread
must be handled separately as you can't make the QThread
object a parent of a resource managed by it - QThread
lives in the thread where it was created and not in the thread it manages.
More details here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With