Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you design your classes in Qt with a lot of widgets?

Tags:

c++

qt

I ran into the problem of how I should design my classes in Qt, to prevent messy code.

My MainWindow has a lot of Buttons, Labels and other widgets. I don't want to make it too big, and I want to handle the callbacks of button presses in a separate class.

The problem is, I want to pass all the information about the Button presses and string entries to the LineEdits to the class as easy as possible. So, I made a class (Data) which just holds the data.

The other class in my test code is named MainModule, and it just does the main loop and receives the results of the button presses. Also, I have to send the changes, depending on what happened in MainModule, back so that I can set Labels and so on. I did this with both the MainWindow and MainModule class with a pointer to the data class.

Class 4 and Class 3 are just some examples of classes which do some other functionality around my MainModule. Some need more data, and some less, so they either have a reference to Data or they just get some variables passed to them.

Another problem I had was the saving and loading of the data. I have to change a lot in my classes when I add a button or a label. I want to get rid of this high coupling, without having the MainWindow class assume too much responsibility.

UML diagramm

I also heard about the design pattern model-view-controller (MVC) which would handle this easily, but the problem here is I don't get how I can use it when I have the problem that my MainWindow is the View, but also handles all the control at the same time?

like image 462
JAR Avatar asked Nov 26 '22 23:11

JAR


1 Answers

First, you're right to be concerned. You definitely don't want your classes to assume responsibilities which are outside of their primary function. Your classes should each have a specific, and limited in scope, purpose. I would recommend reading Uncle Bob's Clean Code for a great discussion on this.

To your question: I assume you are currently receiving user-actions on QButtons, QLineEdits, etc, by connecting their various signals to your own slots (see Qt Signals and Slots). What you may be missing is that you are not limited to connecting a given signal to just a single slot - you can connect them to multiple slots, across multiple classes.

So, if you have two classes, one UI related and one for data collecting, which both need to receive the click of a button, just connect the click to both slots. Make your data collecting class inherit QObject so that it has the signal/slots mechanism.

As an example, here's a mock-up of the image (borrowed from the Qt link above). I added the signal drawn in red:

enter image description here

like image 58
coulomb Avatar answered Feb 17 '23 01:02

coulomb