Search code examples
c++qtqmapqgraphicstextitem

Application stops responding when using QMap to store objects


A friend of mine and I are trying to make a game in C++ using Qt. We want to store a few QGraphicsTextItem in a QMap to access them during runtime. I've pasted the relevant parts of our code here, and our problem is that the program stops responding.

Game.cpp

int players = 6;

QGraphicsRectItem * overviewBox = new QGraphicsRectItem();
overviewBox->setRect(0, 0, 782, 686);
scene->addItem(overviewBox);

for(int i = 1; i <= players; i++) {
    Container * ovContainer = new Container(overviewBox);
    ovContainer->Overview(i, faceNo);
    ovContainer->setPos(0, 0 + 110 * (i - 1));

    info->textBoxMap[i-1] = ovContainer->textBox->playerText; // Program stops responding here
}

GameInfo.h

#ifndef GAMEINFO_H
#define GAMEINFO_H


#include "TextBox.h"
#include <QMap>

class GameInfo {
public:
    GameInfo();

    QMap<int, QGraphicsTextItem *> textBoxMap;
};

#endif // GAMEINFO_H

None of us have much experience using C++ or Qt, and we would appreciate any help.


Solution

  • Unless you are missing some code in your code snippet, then your QMap is not being used correctly. I think you have not allocated (inserted) any QMap items yet? - therefore you are accessing an element that is out of range (i.e. does not exist yet).

    To add items into the QMap you can use insert(), like this (taken from Qt page):

    QMap<int, QString> map;
    map.insert(1, "one");
    map.insert(5, "five");
    map.insert(10, "ten");
    

    Then to read your values back out:

    QString str = map[1];
    //or
    QString str2 = map.value(5);
    

    You don't need to iterate using a for loop but for your code you could do:

    for(int i = 1; i <= players; i++)
    {
           :
           :
        info->textBoxMap.insert(i, ovContainer->textBox->playerText);
    }
    

    note

    If you want to insert items with the same key you will need to use insertMulti(...), otherwise you will just overwrite the value of the key, e.g.:

    QMap<int, QString> map;
    map.insert(1, "test1");
    map.insert(1, "test2");
    

    Here, map[1] will return "test2". But I don't think this is what you want since your players are all going to be unique indexes I assume... but its worth pointing out that insert() with the same index just over-writes the value.