QT: Creating different QGraphicsItems from one slot - c++

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); });

Related

Programming pattern for components that are toggleable at runtime

I'm wondering if there is some kind of logical programming pattern or structure that I should be using if sometimes during runtime a component should be used and other times not. The obvious simple solution is to just use if-else statements everywhere. I'm trying to avoid littering my code with if-else statements since once the component is toggled on, it will more than likely be on for a while and I wonder if its worth it to recheck if the same component is active all over the place when the answer will most likely not have changed between checks.
Thanks
A brief example of what I'm trying to avoid
class MainClass
{
public:
// constructors, destructors, etc
private:
ComponentClass m_TogglableComponent;
}
// somewhere else in the codebase
if (m_TogglableComponent.IsActive())
{
// do stuff
}
// somewhere totally different in the codebase
if (m_TogglableComponent.IsActive())
{
// do some different stuff
}
Looks like you're headed towards a feature toggle. This is a common occurrence when there's a piece of functionality that you need to be able to toggle on or off at run time. The key piece of insight with this approach is to use polymorphism instead of if/else statements, leveraging object oriented practices.
Martin Fowler details an approach here, as well as his rationale: http://martinfowler.com/articles/feature-toggles.html
But for a quick answer, instead of having state in your ComponentClass that tells observers whether it's active or not, you'll want to make a base class, AbstractComponentClass, and two base classes ActiveComponentClass and InactiveComponentClass. Bear in mind that m_TogglableComponent is currently an automatic member, and you'll need to make it a pointer under this new setup.
AbstractComponentClass will define pure virtual methods that both need to implement. In ActiveComponentClass you will put your normal functionality, as if it were enabled. In InactiveComponentClass you do as little as possible, enough to make the component invisible as far as MainClass is concerned. Void functions will do nothing and functions return values will return neutral values.
The last step is creating an instance of one of these two classes. This is where you bring in dependency injection. In your constructor to MainClass, you'll take a pointer of type AbstractComponentClass. From there on it doesn't care if it's Active or Inactive, it just calls the virtual functions. Whoever owns or controls MainClass is the one that injects the kind that you want, either active or inactive, which could be read by configuration or however else your system decides when to toggle.
If you need to change the behaviour at run time, you'll also need a setter method that takes another AbstractComponentClass pointer and replaces the one from the constructor.

Organization of the QT Code

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();
}

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.

c++ GUI Events/Messaging Design

So, I'm making a simple game using DirectX 9 and C++. I looked at the SDK's GUI, but I think I can implement something simpler.
All I want are windows, labels, buttons, textboxes, and checkboxes.
I've created a base class GUIObject, that all inherit from. It includes basics like size and focus and whatnot. Then the derived classes, GUILabel for example, all define render(), update() and whatnot.
My question is how to handle events, like clicks? I had it working with GUILabel::Click() defining every possibility based on the current instance's text member value. It felt wrong and I realized that every single label that needed to be clicked would have to be defined in the GUILabel class. I'd like to move that to each game state's code.
So, I briefly tried making the GUILabel::Click() take a function pointer as an argument. But then I realized I needed to have the state's class member method as static (not really possible, unless everything in it is static as well, right?) or also pass it a GUIObject class as well. Is that the way to go?
Could I define a derivation of GUILabel (or button, or whatnot) within a game state and just override whichever actions I needed? And then do that for whatever controls I need in that state?
What is the proper way to implement event handling?
You might want to look into using a signaling library such as boost::signals to allow you the flexibility of defining the interface between your GUI objects and the underlying events that each callback will trigger. It can also come in handy for the reverse relationship where you need GUI elements such as status indicators, etc. to respond to underlying events.
For callbacks/click events i would go with boost::function/boost::bind.
In my GUI framework I used to have two different abstract classes InputHandler and Renderable for handling touches and rendering. This leads to a design where components which don't need to be clickable (like UILabel) wont need to implement useless methods.
HTH,
Alex

custom GUI objects

in a C++ program I have graphs to which I'd like to add some objects. Those can be, for example, common "stand-alone" objects like text, lines etc, or more "smart" objects of different types which act differently and can be connected to an external model to read/write its state.
The simplest thing I have in mind is creating a common interface to all objects with virtual functions like Draw() etc, but the objects can be essentially different (just like text box and scroll bar are different and thus have a different interface). On the other hand, If I don't create a common interface, I'll need to dispatch on objects types, which is usually considered bad practice in C++.
All this is supposed to be kept simple, for example creating widgets and custom message queues would be an overkill, but I want to make something easy to support/extend.
I know there are many patterns for GUI, such as MVC, MVP etc, but those are very general and I'm a bit lost, so if you could give me some directions (or even better, a reference to inspire from) that would be helpful! Thanks.
One possibility would be to use multiple inheritance. Define a drawable base class that only defines enough to draw a visible object, and require all your drawable objects to derive from that. They might (often will) derive from other base classes as well, to define other interfaces they support; that one will just ensure that every item can be drawn when needed.
For flexibility and scalability, you can use interfaces instead of a single base class. For example extend all objects that can be painted from a IDraw interface. If objects can be updated add and implement a IControl interface and so on. This may look first as an overhead but offers you a good scalability.
Edit:
void* Class::GetInterface(const int id)
{
if (IDraw::GetId() == id)
{
return (IDraw*)this;
}
else if (IControl::GetId() == id)
{
return (IControl*)this;
}
return NULL;
}