Mine field Layout problem (solved).
-
Hi everyone, I've recently started to develope a simple game (mine field) and I already have a problem.
I create a QPushButton "newGame", which purpose is to create a grid of buttons.
I post some lines of the code to help the explanation:@
mine_field::mine_field(QWidget *parent) : QWidget(parent) {QHBoxLayout *menuLayout = new QHBoxLayout();
QPushButton *newGame = new QPushButton(tr("New Game"));
menuLayout->addWidget(newGame);QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addLayout(menuLayout);
setLayout(mainLayout);connect(newGame, SIGNAL(clicked()), this, SLOT(create()));
}void mine_field::create()
{
QGridLayout *buttonLayout = new QGridLayout();
for (int i=0;i<10;++i)
for (int j=0; j<10; ++j){
QPushButton *button = new QPushButton();
buttonLayout->addWidget(button, i, j);
}
mainLayout -> addLayout(buttonLayout);
}
@I get a segmentation fault, I think because mainLayout is not defined in function create().
Anyone can help me?
Thanks. -
Hi and welcome to devnet,
You are shadowing mainLayout in your constructor that's why it crashes in create()
-
Thank for the answer, how can I set mainLayout as global, visible both for constructor and for create() ?
-
Seems you already do have it as a class member. Otherwise you wouldn't be able to compile
-
Yes, I declared it in header file:
@ private:
QHBoxLayout *menuLayout; @So instead of write in constructor:
@ QHBoxLayout *menuLayout = new QHBoxLayout (); @Can I use it as?
@ this->menuLayout @ -
Ok, I resolved the problem just declaring in constructor:
@menuLayout = new QHBoxLayout ();@Thank you for your patience :)
-
You're welcome !
Since you have it working now, please update the thread title by prepending [solved] so the other forum users may know a solution has been found :)