应用程序使用QMAP存储对象时停止响应

Application stops responding when using QMap to store objects

本文关键字:响应 对象 存储 QMAP 应用程序      更新时间:2023-10-16

我和我的一个朋友正在尝试使用QT在C 制作游戏。我们希望将一些QGraphicsTextItem存储在QMap中以在运行时访问它们。我在这里粘贴了代码的相关部分,我们的问题是该程序停止响应。

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

我们没有人使用C 或QT经验太多,我们感谢任何帮助。

除非您缺少代码段中的某些代码,否则您的QMAP无法正确使用。我认为您还没有分配(插入)任何QMAP项目吗? - 因此,您正在访问一个超出范围的元素(即尚不存在)。

要在QMAP中添加项目,您可以使用insert(),如QT页面:

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

然后读出您的值:

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

您不需要使用for for for for for loop进行迭代,但是对于您的代码,您可以这样做:

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

注意

如果要使用相同的密钥插入项目,则需要使用insertMulti(...),否则您只需覆盖密钥的值,例如:

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

在这里,map[1]将返回" Test2"。但是我认为这不是您想要的,因为您的玩家都将成为唯一的索引...但是值得指出的是,具有相同索引的insert()刚好折叠。