在单个变量中检索不同的 Qmap

Retrieve differents Qmap in a single variable

我正在用 Qt 开发游戏。 我的 characters/objects 存储在我的模型 Class 中(我尝试遵循 MVC 模型)。

我为每个对象创建了一个 QMap :

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

但是我想在我的控制器中检索所有这些 QMap,并将它从控制器发送到我的视图的 paintEvent() class。 有没有办法像这样将 QMap 存储在 QList 中:

QList<QMap<int, void*>>

然后施法呢?我正在寻找一种从单个对象访问这些 QMap 的方法。

感谢您的帮助!

您可以使用结构将它们捆绑在一个对象中:

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

虽然拥有指向 QMap 的指针是有效的,但如果您不需要持有指向它的指针,那么我建议不要这样做。

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

这样你就不用担心堆allocations/deallocations。

如果您有支持 C++11 的编译器,那么您可以使用 std::tuple 将项目组合在一起。

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

您可以为所有特定对象保留指向基 class 的指针:

QMap<int, MyBaseClass*> allObjects;

首先,是的,您可以为此目的使用 QList,但是我建议先创建一个接口 class 并在您的 QMap.[=16= 中使用它]

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
}

另一种可能性:

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

如果您愿意,可以按照其他响应者的提示将所有内容封装到一个结构中。

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

QList<MyGameObject> _GameObjects;

如果每个都是相关的(所有对象都使用相同的键),则可以简化为:

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