creating objects in a for()
Hi,
I'm rather new to C++ and now I need a dynamic amount (int i) of buttons. I tried something (where I was sure that it wouldn't work, but just to tell you what I need) like this:
Code:
int i; i=0;
for(;i<9;i++){
label.setText("first line\nsecond line");
label.setAlignment(Qt::AlignTop | Qt::AlignLeft);
label.setGeometry(10*i,80,120,50);
}
I know that normally it would be my job to learn C++ properly, but perhaps you could be so kind and correct the code given above.
Thanks.
Re: creating objects in a for()
Code:
for(int i=0;i<9;i++){
label->setText("first line\nsecond line");
label->setAlignment(Qt::AlignTop | Qt::AlignLeft);
label->setGeometry(10*i,80,120,50);
}
This will more or less work, but two more potential errors are here:
By that code I guess "fenster" is a stack allocated object which can go out of scope. It should be allocated on heap (just like I corrected the labels here)
Code:
label->setGeometry(10*i,80,120,50);
Based on this I guess you are not using layouts, while you probably should.
Re: creating objects in a for()
Quote:
Originally Posted by wysota
This will more or less work, but two more potential errors are here:
By that code I guess "fenster" is a stack allocated object which can go out of scope. It should be allocated on heap (just like I corrected the labels here)
Which means that your code should eventualy look like this *and* compile flawlesly:
Re: creating objects in a for()
Thank you very much, you were a great help!