Reputation: 1615
Since I am not very experienced in the design of object orientated code, I have the following question:
I have a combobox cb_GRAN with 21 entries representing 21 geometries. According to the choice made in cb_GRAN I want start different calculations of the surface of my geometry (actually there is more: more complicated calculatins, on/of-switching of LineEdits etc. but to keep it simple let`s just talk about the calculation of the surface. )
To solve this problem I created a class Geometry and 21 Classes (Geo_1, Geo_2,...Geo_21) which inherit from Geometry. I also have a virtual method
virtual void calculateSurface();
To define which class Geo_x is to create and to calculate the surface I came up with the following idea:
Geometry *GEO;
QVector < Geometry*> qvec_GEO
qvec_GEO << new Geo_1()<< new Geo_2()<< new Geo_3()<<...... << new Geo_21() ;
GEO = qvec_GEO[ui->cb_GRAN->currentIndex()];
GEO->calculateSurface();
Upvotes: 0
Views: 262
Reputation: 794
My Approach would be to define a factory class for your geometries
class GeoFactory{
enum GeometryType { GEO_1, GEO_2, ... );
std::uique_ptr<Geometry> create( GeometryType type );
}
And then add the GeometryType to your combobox items in the data role. On the current changed event you just retrieve the GeometryType from the current index and request the corresponding object from the factory.
Personally i always try to keep out Qt from the actual business logic, i just use for UI.
Upvotes: 0
Reputation: 22588
Question 1: Your solution will probably work well (only based on information you provided).
Question 2: You're totally right, creating instance of all your 21 class if you are going to use only 1 or 2 of them is probably an overkill.
You have to find a solution to instantiate only the needed class. Qt provide a Meta-object system you could use for this. Basically, you will have to use the QMetaType class.
First, you have to register the "Geo_N" classes in the meta-object system. You have many solutions to do that, but maybe the best in your case is to use the declarative macro after your class definition:
class Geo_1 {
Q_OBJECT
void Geo_1();
};
Q_DECLARE_METATYPE(Geo_1);
Please note that Q_OBJECT macro is mandatory if you want to register a class in the meta-object registry.
Then, you will be able to instantiate any registered type dynamically:
// The index of selected class (between 1 and 21)
int geoIndex = ui->cb_GRAN->currentIndex();
// Re-build the corresponding class name
QString typeName = "Geo_" + QString::number(geoIndex);
// Retrieve the type ID corresponding to the type name
int typeId = QMetaType::type(typeName.toStdString().c_str());
// Instantiate the corresponding class
Geometry* geo = (Geometry*) QMetaType::construct(typeId);
Upvotes: 1