Perhaps a rather silly and newbie question but I have been struggling with keeping my QSerialPort serial;
being used within the entirety of the application I am making. (Ughh this is frustrating to explain)
To be more clear I have the aforementioned QSerialPort serial;
established in my MainWindow.cpp
, but as I transition to another form which has a different class (for exampleoperations.cpp
) I am unsure on how to keep and use my serial.*
functions. My mainwindow.cpp form is just a connection settings form which allow you choose the port, baud rate, data bits, parity, etc to be set and once I press my "Open Connection" button, I have the form hidden(this->hide();
) and the operations.cpp form appear.
Any clues on what should I do?
---
I had attempted to use Parent-Child relationship with the classes however, it only started a new QSerialPort serial;
and the connect was lost.
You should factor out a separate
QObject
class that performs communications, and connect other classes to it.A well designed system will never have a UI class own and use a serial port directly. See e.g. this answer for an idea how to separate the communications and the UI.
Let's see what transformations you could do to your code. At present you might have something similar to the below:
The serial-port using functionality is spread across the UI classes, coupling them very tightly with the port. Let's fix that by factoring out the port operations:
Finally, if you're tired of passing the controller around explicitly, we can implement a method akin to
QCoreApplication::instance
to get access to the unique controller instance: