【发布时间】:2015-05-07 09:46:40
【问题描述】:
我有一个用于生成 Qt 场景的卡片项目的代码。这是我到目前为止想出的。调用的成员函数正是您从名称中派生出来的,所以我不需要在这里包含它们。
// creating the cards
int x = 0;
int y = 0;
int line_brake = 0;
for(int i = 0; i < width; i++)
{
for(int j = 0; j < width; j++)
{
card = new Card();
int card_width = card->getWidth();
int card_height = card->getHeight();
if(j == (width-1))
{
line_brake = 1;
}
else if((j != (width-1)) && (line_brake == 1))
{
y += card_height;
card->setPos(x,y);
line_brake = 0;
x = 0 - card_width;
}
else
{
card->setPos(x,y);
x += card_width;
}
scene->addItem(card);
}
}
这是代码运行后我的场景的样子:
可能是什么问题?我需要将卡片放在一个 7*7 的正方形中。这意味着 7 行 7 列,每个字段中都有一张卡片图像。
这就是我的场景在@molbdnilo 的编辑建议后的样子:
// creating the cards
int x = 0;
int y = 0;
int line_brake = 0;
for(int i = 0; i < width; i++)
{
for(int j = 0; j < width; j++)
{
card = new Card();
int card_width = card->getWidth();
int card_height = card->getHeight();
if(j == (width-1))
{
line_brake = 1;
continue;
}
else if((j != (width-1)) && (line_brake == 1))
{
y += card_height;
card->setPos(x,y);
line_brake = 0;
x = 0;
}
else
{
card->setPos(x,y);
x += card_width;
}
scene->addItem(card);
}
}
【问题讨论】:
-
当
j是width - 1时,您正在添加一张尚未设置位置的卡片。 -
我怀疑您的意思是在外部循环标头中使用
height而不是width。 -
@molbdnilo 我在里面添加了
continue;,但问题仍然存在。 -
@Wintermute
width变量是板的宽度,并且始终是宽度*宽度。所以没有高度。 -
@user3710031 也许您可以添加一个您期望场景看起来像什么的描述?我怀疑
x = 0 - card_width会让你把卡片放在窗外。