Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to properly delete QThread?



  • Hi, I have a QThread in my main dialog which is responsible for some processes declared in MyWorker class (inherited from QObject). I wish that when I close the dialog it will automatically delete the thread and MyWorker object. However, each time I close the window I get the message QThread: Destroyed while thread is still running 14:14:16: The program has unexpectedly finished.
    What I try to do is in my dialog's deconstructor, I emit a signal void finished() which is connected to the thread and the object. Nevertheless, it does work. So, what will be the correct way to end the thread and its process?

    connect(this, &Sender::finished, sendThread, &MyThread::deleteLater);
    connect(this, &Sender::finished, &sThread, &QThread::deleteLater);
    connect(this, &Sender::finished, &sThread, &QThread::quit);
    

  • Lifetime Qt Champion

    You have to wait() until the thread had time to shut down. Also you should not connect Sender::finished to deleteLater but the QThread's finished signal to deletedLater.


  • Lifetime Qt Champion

    You have to wait() until the thread had time to shut down. Also you should not connect Sender::finished to deleteLater but the QThread's finished signal to deletedLater.


Log in to reply