ltheron
ltheron

Reputation: 301

Retrieve differents Qmap in a single variable

I am working on a game in Qt. My characters/objects are stored in my model Class (I try to follow the MVC model).

I created a QMap containing for each of the object :

QMap<int, Safe*> *safes;
QMap<int, Mushroom*> *mushroom;
QMap<int, Floor*> *floors;

But then I would like to retrieve all theses QMap in my Controller and send it to the paintEvent() class of my View from the controller. Is there a way to store the QMap in a QList like this :

QList<QMap<int, void*>>

And then cast it ? I am searching for a way to acces to theses QMap from a single object.

Thank you for your help !

Upvotes: 1

Views: 339

Answers (3)

Mohamad Elghawi
Mohamad Elghawi

Reputation: 2124

You could use a struct to bundle them up inside one object:

struct Maps
{
    QMap<int, Safe*> *safes;
    QMap<int, Mushroom*> *mushroom;
    QMap<int, Floor*> *floors;
};

Although it's valid to have a pointer to QMap, if you don't need to hold a pointer to it then I would advise against it.

struct Maps
{
    QMap<int, Safe*> safes;
    QMap<int, Mushroom*> mushroom;
    QMap<int, Floor*> floors;
};

That way you don't have to worry about heap allocations/deallocations.

If you have a compiler that supports C++11 then you can use std::tuple to group items together.

std::tuple<QMap, QMap, QMap> maps (safes, mushroom, floors);

Upvotes: 3

bkausbk
bkausbk

Reputation: 2790

First, yes you can use a QList for this purpose, however I would suggest to create an interface class first and use this in your QMap.

struct GameObjectInterface {
};

class Safe : public GameObjectInterface {};
class Mushroom : public GameObjectInterface {};
class Floor : public GameObjectInterface {};

QMap<int, GameObjectInterface*> _GameObjects;

// Is game object with ID `n` a `Safe`?

Safe* s = dynamic_cast<Safe*>(_GameObjects[n]);
if (s != nullptr) {
    // Yes it is a safe
}

Another possibility:

QList<QMap<int, GameObjectInterface*>> _GameObjects;

And if you want you can capsule everything into one struct as hinted by other responders.

struct MyGameObject {
    QMap<int, Safe*> Safes;
    QMap<int, Mushrooms*> Mushrooms;
    QMap<int, Floor*> Floors;
};

QList<MyGameObject> _GameObjects;

If each are related (same key for all objects) it could be simplified like:

struct MyGameObject {
    Safe* _Safe;
    Mushrooms* _Mushroom;
    Floor* _Floor;
};
QMap<int, MyGameObject*> _GameObjects;

Upvotes: 1

AnatolyS
AnatolyS

Reputation: 4319

You could keep pointer to base class for all your specific objects:

QMap<int, MyBaseClass*> allObjects;

Upvotes: 0

Related Questions