You start by moving almost all of the code you have in the MainWindow constructor into a separate method, something like "buildButtonGrid( int n, int m )". Then you rewrite the code to get rid of all of the hard-coded constants (like "10", "100", and so forth) and replace them with "n", "m", "n + 1", "m + 1", etc. as appropriate. You also get rid of the hard-coded "QPushButton * button[10][10]" and replace it with a class member variable "QVector< QButton * > buttons" or something similar that you resize as needed to hold n*m button pointers.
Finally, you get rid of the absolute positioning ("move( 40 * j, 40 * i)") because the grid control will put the buttons in the necessary places.
When you resize the grid, be sure you also remember to delete the previous buttons.
This piece of code shows that you have a logical error in your thinking, because it looks like you had a problem with indexing into your button array and don't understand why. That's why you had to add the "count" variable. You need to rethink this.
for(i=2;i<n;i++)
{
for(j=0;j<m;j++)
{
if(count<=100)
{
button[i][j]->setMinimumSize(40,40);
button[i][j]->setMaximumSize(40,40);
button[i][j]->move(40*j, 40*i);
button[i][j]->show();
controlsLayout->addWidget(button[i][j], i, j);
count++;
}
}
}
for(i=2;i<n;i++)
{
for(j=0;j<m;j++)
{
if(count<=100)
{
button[i][j] = new QPushButton();
button[i][j]->setMinimumSize(40,40);
button[i][j]->setMaximumSize(40,40);
button[i][j]->move(40*j, 40*i);
button[i][j]->show();
controlsLayout->addWidget(button[i][j], i, j);
count++;
}
}
}
To copy to clipboard, switch view to plain text mode
Bookmarks