Organization of the QT Code - c++

I am writing an application of middle size. I will have many gui components and many classes. However, it is difficult for me to organize the code, to separate the logic, ... For example, let say that I press one button that creates an object of a class and perform a computation on that object. After exiting the slot function of the button, this local object is destroyed. What if I need it in another function later? Defining everything as a global variable in the header file is not a good thing for me. So I was thinking of a static class that contains somehow pointers to all the objects I will need later. Does anybody has a better idea?

How to manage objects inside an application is always a tricky
question. Qt goes down a very object-oriented route and uses reference
semantics implemented through pointer for nearly everything. To
prevent tedious manual memory management Qt organizes everything into
Object Trees. This
is augmented by Qt own
object model that adds
some dynamic capabilities.
If you want to go down that route, stick to everything Qt provides. It
is much more similar to Java than the usual C++ approach and might be
more comforting for beginners and maybe suits your application
domain. It tightly ties your code to Qt and will make it hard to
separate from it.
One other approach means to simply forgo all Qt stuff and work out the
core logic of your application. Develop it in pure C++ and than have a
thin layer that ties this logic into your Qt application through
signals and slots. In such an approach you would opt to use more
value-semantics.
For your concrete example of creating an algorithm and keeping it
around. The Qt approach:
class MyAlgo : public QObject {
Q_OBJECT
public:
MyAlgo(QObject* o) : QObject(o) { }
virtual compute();
};
// use it in a mainwindow slot
void MainWindow::executeAlgorithm(const QString& name) {
MyAlgo* algo = this->findChild<MyAlgo*>(name);
if(!algo) {
// not found, create
algo = new MyAlgo(this); // make mainwindow the parent of this algo
algo->setName(name); // QObject name property
}
algo->compute();
}

Related

QT: Creating different QGraphicsItems from one slot

I have some classes inherited from QGraphicsItem, I also have buttons in my interface. Right now, when I press a button, an item is created in the scene. I have such signal/slot system for all of my classes, so as a result I have a lot of slot functions that are very similar, and the only difference is in the type of objects they create. Is this a good programming practice or not, because it doesn't look like it. Is there a way to simplify this?
Armchair is a class inherited from QGraphicsItem
armchair is an object of this class
this is a code example of such slot function
void MainWindow::armchairButton_clicked()
{
scene_preview->clear();
armchair = new Armchair();
scene_preview->addItem(armchair);
}
There is no general fixed rule for this, just the DRY principle (Don't Repeat Yourself).
In general, every button has a distinct function, so there must be some code to distinguish those.
Depending on how much code is common and how much is individual, you need to find a good balance.
In your case, you seem to only have 1 thing to change (the object type to add) and some common code for cleaning. This could be separated, e.g.
void MainWindow::replaceSceneObject(QGraphicsItem *i)
{
scene_preview->clear();
scene_preview->addItem(i);
}
void MainWindow::armchairButton_clicked()
{
replaceSceneObject(new Armchair);
}
As you use manual connects, you actually don't need separate slots for this, but could use lambdas in the connect calls, e.g.:
connect(armchairButton, &QPushButton:clicked, [=]{ replaceSceneObject(new Armchair); });

How can interface return an unknown type?

I'm trying to make a cpp interface class (pure virtual) declare a function that all derived classes must implement. However because the interface class is trying to be ignorant of implementation details, it doesn't know about the type of the returned object, and would like to delegate that to the derived class. The specific type of the returned object is handled by the derived class.
class UIInterface
{
// Should not know about QWidget
// Would like to defer return type until derived class which implements interface
QWidget *getWindow() = 0;
}
class QUIManager : public UIInterface
{
QWidget *getWindow() override {return m_widget;}
}
class XUIManager : public UIInterface
{
XWidget *getWindow() override {return m_widget;}
}
Except UIInterface should not know about QWidget. In some future version, the UIManager might be an XUIManager which returns a different type of window. If possible, I'd like to avoid returning std::any or void * followed by casting.
This pattern keeps showing up in my code, so I'm probably doing something wrong.
Edit based on comments:
My code is experimental, so although I'm using Qt as the UI for now, it's conceivable that may change, for example to use an immediate mode package, or in any case to separate the core logic from the UI. The core logic, may, for example, be accessed from just a console with no UI. Likewise, I'm using Qt's model/view and database classes.
Some examples:
The core needs to tell the UI to open and close windows. I've concluded in most cases that the core does not need to blindly shuffle naked UI pointers, so perhaps this use case is no longer that important.
The core needs to be able to glue database, model, and view together, without these latter three items knowing about each other, even though all three latter items may be specific to Qt or some other framework, or split up, such as using sqlite3 standalone and delegating model/view to Qt. For example, core needs to tell database interface to open a sqlite3 file, ask the modelcreator to create a model based on this, then pass model to UIManager to create the view. In no case does the core need to know specific types, and it would probably suffice to pass pointers around, but this seems like it's not the C++ way these days.
Although for now the track is C++, at some point the core itself might be implemented in a language better suited to the core algorithmic functions, eg Julia, Common Lisp, etc., which will introduce an impedance mismatch with Qt, so I'm trying my best to ensure the core can blindly call some high level functions while still serving as the central hub for the application.
Two options come in my mind, depending what fit better in your project:
1) Use a placeholder for return type:
class UIInterface
{
Widget* getWindow() = 0;
}
you can define in other file using Widget = QWidget. You can hange the alias or even implement your class Widget later and the whole UIInterface will not change. In this case you're just hiding the real type to the layout of your class.
2) You shoulde use a template class like
template<typename T>
class UIInterface
{
T* getWindow() = 0;
}
BUT there are downsides for No.2: you cannot use anymore UIInterface as interface without specifying T, and you're actually to state thatQWidget is the concrete type for T in your code.
Since you wrote "the interface might change in future" and not "I would create an interface regardless of the concrete widget type" I guess the option that fit you better is No.1

QT: Private member instead of inheritance? What is the reason? Is this a specific concept?

Some time ago I programmed a GUI with QT Designer / QT Creator.
For this question I will first state a schematic of how the general process of creating a GUI with the mentioned IDE works:
Creating the design with the QT Designer -> Get .ui files
The .ui files are translated into header files and you especially get something like "UIbasisclass.h" (with class UIbasisclass) .
You create something like an "UIsubclass.h" (with class UIsubclass) yourself making one private member UIbasisclass ui.
Code within class UIsubclass:
...
private:
Ui::UIbasisclass ui;
...
Finally you will create an object of UIsubclass in the main method -> Code:
...
UIsubclass *MyGUI = new UIsubclass();
...
where the constructor of UIsubclass consists among other code of:
...
ui.setupUi(this);
...
In short: We have a UIsubclass that is mostly responsible for applicational methods, but also has a private member of UIbasisclass named ui that consists mostly of design code.
When we create an object of UIsubclass its private member UIbasisclass ui is initialized within the constructor of UIsubclass with the object of UIsubclass itself (?). [see: this pointer]
My questions are now:
Why isn't there used inheritance in the way that UIsubclass inherits from UIbasisclass? Instead one object of UIbasisclass becomes member of UIsubclass.
Is this some specific advantageous concept (if yes which advantages has it or how is it named?) or is it "just" a necessity of the QT code structure?
Let me know if I have to specify my questions or if there are any questions.
You can do with private inheritance, it is even documented in Qt documentation.
The use of a private member for ui is the default because of the templates used by Qt Creator, Qt itself does not care.
Why isn't there used inheritance in the way that UIsubclass inherits from UIbasisclass?
You're asking us about why you didn't do it in your own code? Just do it. It's up to you. It truly is your code. You are responsible for its design. If you're using a template, it's there to help you get started, but not to design your software for you. The responsibility is yours, and yours only.
it "just" a necessity of the QT code structure?
There is no such necessity. The Ui class is a POD class with a bunch of pointers and one method. Nothing much to it. If you want to privately inherit from it: go right ahead.
Because with a private member you can forward declare the generated class:
namespace Ui {
class MyForm;
}
class Foo {
private:
Ui::MyForm *ui;
};
and on the .cpp file you insert the include.
this way all of the possible includes of this file will not have to preprocess that file again.

Qt - proper design of application code

It was hard for me to search for related topic, so here is my question. I started using Qt like two days ago, and therefore I don't have any clue how to make it working (on the code-side).
[offtopic]
Here's some history: at first I thought about separating my application's logic from its appearance. I had some core classes, another ones for GUI (displaying and controlling), and some kind of "bridges" between to, for example, move data from class A which had std::list members to class B : public QAbstractListView, which had QStringList. But I gave up, when I had to use more and more Qt code (HTTP requests, disk I/O, regex). My code started looking like a mess, co I thought about refactoring my code.
(Anyways, is it a good idea to merge these two things - application logic into Qt (sub)classes?)
[/offtopic]
And I came to another problem and it's finally related to question in topic: is it better (say, Qt-way), for example, to have a class with private member QWebPage and some public methods, slots and signals to operate on it or simply to add my functionality in subclass of QWebPage?
Inheritance is one of the greatest things of OOP, if used correctly.
A "subclass", in all good OO designs, has to obey a simple rule: IS the child a KIND OF parent? That is usually called, in OOP literature, a "is a" relationship.
And more important: the child has always to do two things: specialize a generic behavior, or extend the functionality of the father. I consider it a code smell when a subclass does neither.
That said, your decision has nothing to do with Qt, or with what's programatically better or worse. It should make sense.
An example: If you had a QLabel that had to show the score of a game, and only that, it could be a good idea to do something like
class MyScoreBoard : public QLabel
{
private:
int scoreP1;
int scoreP2;
Game *_g;
public:
MyScoreBoard(QWidget *parent = 0) :
QLabel(parent)
{
scoreP1 = 0;
scoreP2 = 0;
connect(_g, SIGNAL(scoreChanged(int,int)), this, SLOT(updateScore(int,int)));
}
public slot:
updateScore(int a, int b) {
scoreP1 = a;
scoreP2 = b;
this->setText(QString::number(scoreP1) + "x" + QString::number(scoreP2));
};
};
On the other hand, if your scoreboard had some lights on top of it, that should blink whenever the score had changed, if it had one label for each player, that had to change its color depending on the score, then it would be better to create a ScoreBoard class that HAD two labels, HAD two lights, and then implement the intended behavior.
Bottom line is: inherit if it makes sense on your design
Wikipedia has a good small article about an anti-pattern that appears when inheritance is used without care.

Is creating a base class for all applications of a particular type good design?

I am trying to write a graphics application in C++. It currently uses OGRE for display, but I'd like it to work with Irrlicht or any other engine, even a custom rendering engine which supports my needs. This is a rather long question, so I'd appreciate help on re-tagging/ cleanup (if necessary). I'll start with a little background.
The application has three major states:
1. Display rasterized scene
2. Display a ray traced version of the same scene
3. Display a hybrid version of the scene
Clearly, I can divide my application into four major parts:
1. A state management system to switch between the above modes.
2. An input system that can receive both keyboard and mouse input.
3. The raster engine used for display.
4. The ray tracing system.
Any application encompassing the above needs to be able to:
1. Create a window.
2. Do all the steps needed to allow rendering in that window.
3. Initialize the input system.
4. Initialize the state manager.
5. Start looping (and rendering!).
I want to be able to change the rendering engine/state manager/input system/ ray tracing system at any time, so long as certain minimum requirements are met. Imho, this requires separating the interface from the implementation. With that in mind, I created the interfaces for the above systems.
At that point, I noticed that the application has a common 'interface' as well. So I thought to abstract it out into an ApplicationBase class with virtual methods. A specific application, such as one which uses OGRE for window creation, rendering etc would derive from this class and implement it.
My first question is - is it a good idea to design like this?
Here is the code for the base class:
#ifndef APPLICATION_H
#define APPLICATION_H
namespace Hybrid
{
//Forward declarations
class StateManager;
class InputSystem;
//Base Class for all my apps using hybrid rendering.
class Application
{
private:
StateManager* state_manager;
InputSystem* input_system;
public:
Application()
{
try
{
//Create the state manager
initialise_state_manager();
//Create the input system
initialise_input_system();
}
catch(...) //Change this later
{
//Throw another exception
}
}
~Application()
{
delete state_manager;
delete input_system;
}
//If one of these fails, it throws an
//exception.
virtual void initialise_state_manager() = 0;
virtual void initialise_input_system() = 0;
virtual void create_window() = 0;
//Other methods.
};
#endif
When I use OGRE, I rely on OGRE to create the window. This requires OGRE to be initialised before the createWindow() function is called in my derived class. Of course, as it is, createWindow is going to be called first! That leaves me with the following options:
1. Leave the base class constructor empty.
2. In the derived class implementation, make initialising OGRE part of the createWindow function.
3. Add an initialize render system pure virtual function to my base class. This runs the risk of forcing a dummy implementation in derived classes which have no use for such a method.
My second question is- what are your recommendations on the choice of one of these strategies for initialising OGRE?
You are mixing two unrelated functions in one class here. First, it serves as a syntactic shortcut for declaring and initializing StateManager and InputSystem members. Second, it declares abstract create_window function.
If you think there should be a common interface - write an interface (pure abstract class).
Additionally, write something like OgreManager self-contained class with initialization (looping etc) methods and event callbacks. Since applications could create and initialize this object at any moment, your second question is solved automatically.
Your design may save a few lines of code for creating new application objects, but the price is maintaining soup-like master object with potentially long inheritance line.
Use interfaces and callbacks.
P.S.: not to mention that calling virtual functions in constructor doesn't mean what you probably expect.
Yes, that is a good design, and it is one that I use myself.
For your second question, I would remove anything from the base constructor that has any possibility of not being applicable to a derived class. If OGRE wants to create the window itself then you need to allow it to do that, and I don't think that it makes sense to initialize OGRE in createWindow (it's misleading).
You could add an initialize render system virtual method, but I think you should just leave that task to the derived class's constructor. Application initialization is always a tricky task, and really, really difficult to abstract. From my experience, it's best not to make any assumptions about what the derived class might want to do, and just let it do the work itself in any way that it wants.
That said, if you can think of something that will absolutely apply to any conceivable derived class then feel free to add that to the base constructor.