I'm trying to figure out how to emit Signals from a thread to be captured by Slots in the main GUI thread. The thread is used to read serial port data. The thread is NOT a QThread. It's a generic Win32 thread created via CreateThread().

The Win32 thread is passed a pointer to a Serial class object. This object has a ThreadProc member function in which the thread runs. The Serial class inherits from QObject and declares the Signal member function.

The connection between the Signal and Slot is made in the main GUI window constructor. If I leave the connection type out so it picks Automatic, I can emit the Signal from the Serial object as long as it is called from the main GUI thread (as when I'm configuring the Serial object before starting the thread). However, any calls to emit the Signal from within the thread do not arrive at the Slot. If I change the connection type to QueuedConnection, none of the Signals make it to the Slot. Not even the ones called from within the main GUI thread.

What is this Qt newbie doing wrong? Using Qt 4.7.


Here are some code snippets:
Qt Code:
  1. #include <QObject>
  2. class Serial : public QObject
  3. {
  4. Q_OBJECT
  5.  
  6. public:
  7. Serial();
  8. virtual ~Serial();
  9.  
  10. void Run();
  11.  
  12. protected:
  13. static DWORD WINAPI ThreadProc (LPVOID lpArg); // 'lpArg' is a pointer to an instance of this class
  14. DWORD ThreadProc (void); // run-loop of the thread, called by the above static function.
  15.  
  16. signals:
  17. void SerialEventSignal(unsigned int event);
  18. };
To copy to clipboard, switch view to plain text mode 
Qt Code:
  1. void Serial::Run()
  2. {
  3. emit SerialEventSignal(1); // works with Automatic connection, fails with QueuedConnection
  4. DWORD dwThreadId = 0;
  5. m_hThread = ::CreateThread(0,0,ThreadProc,LPVOID(this),0,&dwThreadId);
  6. }
  7.  
  8. DWORD WINAPI Serial::ThreadProc(LPVOID lpArg)
  9. {
  10. Serial* pThis = reinterpret_cast<Serial*>(lpArg);
  11. return pThis->ThreadProc();
  12. }
  13.  
  14. DWORD Serial::ThreadProc (void)
  15. {
  16. emit SerialEventSignal(2); // Always fails
  17. while (true)
  18. {
  19. // do stuff
  20. }
  21. }
To copy to clipboard, switch view to plain text mode