gpt4 book ai didi

c++ - 使用 QMap 存储对象时应用程序停止响应

转载 作者:太空狗 更新时间:2023-10-29 21:37:21 26 4
gpt4 key购买 nike

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

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(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() 具有相同的索引只是覆盖值(value)。

关于c++ - 使用 QMap 存储对象时应用程序停止响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37909495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com