title: How to relaunch a thread in Qt?
body: <p>I'm using a separate thread for serial port communication. This thread should launch when we want to connect with serial port and finish when there was an error/disconnection. </p>
  
  <p>The issue is that if the thread has finished once, it doesn't relaunch the next time we want to reconnect. </p>
  
  <pre><code>SerialIO::SerialIO(SettingsDialog *settings) :  //Worker. Extends QObject
      settings(settings)
  {
      serial = new QSerialPort(this);
  }
  
  SerialIO::~SerialIO()
  {
      serial-&gt;close();  
      //something else?  
  }
  
  
  /* PUBLIC SLOT */
  void SerialIO::connectSP()
  { 
      /* connects with some port, if not succesfull, emits an error signal */ 
  }
  </code></pre>
  
  <hr>
  
  <pre><code>MainWindow::MainWindow(QWidget *parent)
      : QWidget(parent)
  {
      //...
      serialio = new SerialIO(settings);
      serialio-&gt;moveToThread(&amp;thread);  
  
      QObject::connect(&amp;thread,SIGNAL(started()),serialio,SLOT(connectSP()));
      QObject::connect(&amp;thread,SIGNAL(finished()),serialio,SLOT(deleteLater()));  
      QObject::connect(serialio,SIGNAL(error(const QString)),this,SLOT(handleError(const QString&amp;)));      
      //...
  
  }
  
  void MainWindow::connect()   
  {
      if(!thread.isRunning()){              
          thread.start();
      }
  
  }
  
  void MainWindow::handleError(const QString &amp;msg){
      QMessageBox::information(this, "Error", msg);
      if(thread.isRunning()){
          thread.quit();
          thread.wait();
      }
  }
  </code></pre>
  
  <p>It seems that the thread doesn't finish properly, but I've already checked the thread is not running! Then the program finish unexpectedly.</p>
  
  <hr>
  
  <p>Solution:</p>
  
  <pre><code>QObject::connect(&amp;thread,SIGNAL(started()),serialio,SLOT(connectSP()));
  QObject::connect(&amp;thread,SIGNAL(finished()),serialio,SLOT(disconnectSP()));
  QObject::connect(serialio,SIGNAL(bye()),&amp;thread,SLOT(quit()));
  </code></pre>