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:
#include <QObject>
{
Q_OBJECT
public:
Serial();
virtual ~Serial();
void Run();
protected:
static DWORD WINAPI ThreadProc (LPVOID lpArg); // 'lpArg' is a pointer to an instance of this class
DWORD ThreadProc (void); // run-loop of the thread, called by the above static function.
signals:
void SerialEventSignal(unsigned int event);
};
#include <QObject>
class Serial : public QObject
{
Q_OBJECT
public:
Serial();
virtual ~Serial();
void Run();
protected:
static DWORD WINAPI ThreadProc (LPVOID lpArg); // 'lpArg' is a pointer to an instance of this class
DWORD ThreadProc (void); // run-loop of the thread, called by the above static function.
signals:
void SerialEventSignal(unsigned int event);
};
To copy to clipboard, switch view to plain text mode
void Serial::Run()
{
emit SerialEventSignal(1); // works with Automatic connection, fails with QueuedConnection
DWORD dwThreadId = 0;
m_hThread = ::CreateThread(0,0,ThreadProc,LPVOID(this),0,&dwThreadId);
}
DWORD WINAPI Serial::ThreadProc(LPVOID lpArg)
{
Serial* pThis = reinterpret_cast<Serial*>(lpArg);
return pThis->ThreadProc();
}
DWORD Serial::ThreadProc (void)
{
emit SerialEventSignal(2); // Always fails
while (true)
{
// do stuff
}
}
void Serial::Run()
{
emit SerialEventSignal(1); // works with Automatic connection, fails with QueuedConnection
DWORD dwThreadId = 0;
m_hThread = ::CreateThread(0,0,ThreadProc,LPVOID(this),0,&dwThreadId);
}
DWORD WINAPI Serial::ThreadProc(LPVOID lpArg)
{
Serial* pThis = reinterpret_cast<Serial*>(lpArg);
return pThis->ThreadProc();
}
DWORD Serial::ThreadProc (void)
{
emit SerialEventSignal(2); // Always fails
while (true)
{
// do stuff
}
}
To copy to clipboard, switch view to plain text mode
Bookmarks