PDA

View Full Version : Serial port read/write using a multithreaded Qt app



Aham
24th November 2016, 13:53
The Qt application I am required to develop, needs to have 2 threads.

thread-1: read data from a serial port and pass it onto thread 2
thread-2: display the raw data it received (sent by thread-1)

From my very limited knowledge of Qt, I understand thread-1 is the worker thread and thread-2 is the main GUI thread.

What is the design approach for implementing this application?

Lesiok
24th November 2016, 14:26
The second thread (with serial port) is unnecessary. Just use signal readyRead to get data from serial port and display it.

Aham
25th November 2016, 07:02
Thanks, Lesiok.

What you are saying is correct and I understand that.

But, there is a requirement for 2 threads because more functionalities will be added in future that require 2nd thread.

Before we add many functionalities, I'm just trying to implement the basic framework with 2 threads.

Lesiok
25th November 2016, 08:55
This use a signals and slots mechanism for communicating between threads. And yes, thread 1 is worker and thread 2 is GUI (main) thread.

Aham
25th November 2016, 12:14
Ok, cool. I'm new to Qt and have been reading up some literature about it. So, do you think I should use a QueuedConnection to pass data from worker to main thread? Can you give me a basic structure of the code that I can start with for my application?

Lesiok
25th November 2016, 12:42
Yes, You should use a QueuedConnection. It is a default when sender and receiver are in two threads.

Aham
25th November 2016, 14:00
I've installed Qt 5.7 on Windows (8.1). I'm not getting QThread option (as a base class) while I try to add a new class to a project? What could be the reason?

Lesiok
25th November 2016, 14:59
Here (http://doc.qt.io/qt-5/qthread.html#details) You have an example how to deal with QThread. Note that in first example the Worker does not inherit the QThread. This method is better because you can easily use the Worker in any thread.

Aham
25th November 2016, 15:58
Ok, I will. Thanks, Lesiok.