有效的方式来创建标签数组 [英] Efficient way to make an array of labels
问题描述
我在做一个棋盘游戏,我需要在我的gui中显示一个15 x 15的数组。我决定去与包含数组的一个元素的个别标签。这意味着我有很多标签。我给每个标签的名称tile_0_0,第一个0是行,第二个0是列。这在qt很容易做。
I'm making a board game and I need to display a 15 x 15 array in my gui. I decided to go with individual labels which contains one element of the array. This means I do have quite a lot of labels. I gave each label the name "tile_0_0" with the first 0 being the row and the second 0 being the column. This was quite easy to do in qt.
然而问题是,我现在不能简单地使用2个forloops访问每个磁贴,因为你不能使用变量名称。 (tile_i_j不存在)。为了解决这个问题,我决定创建一个包含每个标签的数组。但是,由于前面提到的问题,我无法初始化数组的效率。
The problem however is that I ofcourse can't simply use 2 forloops to access each tile since you can't use variables in names. ("tile_i_j" does not exist.) To solve this I decided to make an array which contains each and every label. I however cannot initialise the array efficient because of the earlier mentioned problem.
所以问题是:如何避免写一个巨大的代码块?
当前代码的一小部分:
So the question is: How can I avoid having to write a giant block of code? A small piece of the current code:
Ui::BoardView *ui = new UI::BoardView; // BoardView is my class
QLabel* m_boardLbArray[8][8];
m_boardLbArray[0][0] = ui->tile_0_0;
m_boardLbArray[0][1] = ui->tile_0_1;
m_boardLbArray[0][2] = ui->tile_0_2;
m_boardLbArray[0][3] = ui->tile_0_3;
m_boardLbArray[0][4] = ui->tile_0_4;
// ...
注意:对不起,
推荐答案
这听起来像是你创建的你的瓷砖(QLabels)在Qt设计器;实现这一点的一个更清洁的方法是以编程方式创建它们。您可以在Designer中的您想要的位置为表单添加一个网格布局,然后执行:
It sounds like you are creating your tiles(QLabels) in Qt Designer; A cleaner way to achieve this is to create them programatically. You can do something like add a Grid Layout to your form in Designer in the location you want them, and then do:
QGridLayout *layout = ui->gridlayout;
QLabel* m_boardLbArray[8][8];
for(int row=0; row<8; row++)
for(int col=0; col<8; col++)
{
m_boardLbArray[row][col] = new QLabel(this);
m_boardLbArray[row][col]->setText(tr("This is row %1, col %2")
.arg(row).arg(col));
layout->addWidget(m_boardLbArray[row][col], row, col);
}
这篇关于有效的方式来创建标签数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!