简体   繁体   中英

Qt avoiding circular dependency

I have a Qt application with a main class GUIApplication which inherits from QMainWindow as shown below. The GUI has a start button, stop button and a QGraphicsScene.

My application will read data from the serial port and other stuff and draw on the QGraphicsScene according to what is received.

My main GUI class knows about my serial port class as it must initialse it on press of the start button etc. That is fine. My serial port class however must also must be able to communicate with my GUI class as it must update the QGraphicsScene on reception of data and other stuff.

My question is , is it a bad design for my serial port class to know about the GUI class also. Isn't this a form of circular dependency between the two classes? I plan to have a member of my serial port class a pointer to the GUI class. Is this the only way to do it , or should I register a callback in the serial port class instead, to decouple the classes? Any help is appreciated thanks.

// GUI class
#include "MySerial.h "
class GUIApplication : public QMainWindow
{
    Q_OBJECT

public:
//.........

o_o

// Serial port class
#include "GUIApp.h "
class MySerial
{

public:
//..............
//write something on GUI`

It is a bad design. Your serial port class has nothing to do with GUI by nature and as such should be separated from it - apart from circular dependencies, you make it much less flexible that way and limit its usability. One day you might want to use it in a console application and if you wrote the class in such a way that it must be aware of the GUI class, you would have to modify it just to make it work with console and either have two versions that would differ only regarding UI, which doesn't make much sense, or add Qt as dependency even though you would not need it in console app if you wouldn't want to break the compatibility, which doesn't make much sense either.

Much better solution is sending some signal from your serial port class or some meaningful return code after the data is received, and then make the GUI class catch this value and update QGraphicsScene itself. That way you also get rid off the circular dependency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM