Why you check the serial port with a timer instead of doing it directly in the run() of the thread?

I use QextSerialPort and I check the available data in a thread like this:

Qt Code:
  1. class ReceiveThread : public QThread
  2. {
  3. Q_OBJECT
  4.  
  5. public:
  6. ReceiveThread(QextSerialPort *adrPort);
  7. ~ReceiveThread();
  8.  
  9. void stopReceiving();
  10.  
  11. protected:
  12. void run();
  13.  
  14. signals:
  15. void dataReceived(const QByteArray); //!< Data Available from the QextSerialPort
  16.  
  17. private:
  18. QextSerialPort *d_port; //!< Reference to the serial port to monitor
  19. QMutex mutex; //!< Mutex lock
  20. bool stopped; //!< Specify if the thread is running or not (it is needed to stop the thread)
  21. };
  22.  
  23. ReceiveThread::ReceiveThread(QextSerialPort *adrPort)
  24. : d_port(adrPort), stopped(false)
  25. {
  26. }
  27.  
  28. ReceiveThread::~ReceiveThread()
  29. {
  30. if (isRunning())
  31. {
  32. stopReceiving();
  33. wait();
  34. }
  35. }
  36.  
  37. void ReceiveThread::stopReceiving()
  38. {
  39. stopped = true;
  40. }
  41.  
  42. //! The Receive Thread Loop
  43. void ReceiveThread::run()
  44. {
  45. QByteArray data;
  46. int bytesAvailable;
  47. data.reserve(MAX_BUFFER_SIZE);
  48.  
  49. while(!stopped)
  50. {
  51. mutex.lock();
  52. bytesAvailable = d_port->bytesAvailable();
  53. if (bytesAvailable > 0)
  54. data.append(d_port->read((bytesAvailable<MAX_BUFFER_SIZE)? bytesAvailable: MAX_BUFFER_SIZE));
  55. mutex.unlock();
  56.  
  57. if (bytesAvailable)
  58. qDebug() << tr("ReceiveThread: %1").arg(bytesAvailable);
  59.  
  60. if (!data.isEmpty())
  61. {
  62. emit dataReceived(data);
  63. qDebug() << tr("ReceiveThread: Emitted Data Received");
  64. qDebug() << tr("ReceiveThread: Data: 0x%1").arg((QString)data.toHex());
  65. data.clear();
  66. }
  67.  
  68. msleep(RECEIVE_THREAD_SLEEP_TIME);
  69. }
  70. }
To copy to clipboard, switch view to plain text mode 

To use this class you only nead to istantiete the class and call the run() method to start the monitoring of the serial port.
To stop the monitoring you must call the stopReceiving() method.

The data received is emitted with the signal dataReceived(const QByteArray &), so you have to connect this with a slot to manage the data received.

WARNING
This class does not perform any check on the QextSerialPort provided, you have to perform these check before starting the Receive Thread. Also you have to stop the Receive Thread before close the QextSerialPort.

So, instead to instantiate the Thread directly in the Main you have to instantiate it in your MainWindow after create and open the serialport.