Trouble with QSerialPort + Threads
-
Hi,
I've been having a nightmare of a time trying to setup signals / slots with my QSerialPort that is created and run on a separate thread. I have 2 threads: my main UI / program thread and a thread for handling a constant stream of serial data and writing back to the port.
My serial thread inherits QThread. In this thread's run() function, I create a new port @serial = new QSerialPort(this);@ and then attempt to connect signals and slots @connect(serial, SIGNAL(readyRead()), this, SLOT(processSerialData()));@ however this gives me the error: @QObject: Cannot create children for a parent that is in a different thread.
(Parent is SerialThread(0x290f090), parent's thread is QThread(0x4a5cc0), current thread is SerialThread(0x290f090)@The port connects fine after this, but the signals / slots setup doesn't seem to work at all... I've seen related posts about this, but haven't been able to solve it...
Any help would be very much appreciated!
-
Please make sure you read the latest documentation of "QThread":http://qt-project.org/doc/qt-5/qthread.html.
Especially that part:
[quote]It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of QThread's queued slots will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed QThread.
When subclassing QThread, keep in mind that the constructor executes in the old thread while run() executes in the new thread. If a member variable is accessed from both functions, then the variable is accessed from two different threads. Check that it is safe to do so.[/quote]I suspect that is what hits you here.
-
Great, thanks for that, will take a look!
-
What's more is that the line that fails is
@serial = new QSerialPort(this);@
QSerialPort lives in the newly created thread, but your QThread object (this) doesn't. You cannot have a parent in another thread, as the error message suggests.