PDA

View Full Version : creating objects in a for()



phil_
20th January 2006, 20:14
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:


int i; i=0;
for(;i<9;i++){
QLabel label(&fenster);
label.setFrameStyle(QFrame::Panel | QFrame::Sunken);
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.

wysota
20th January 2006, 21:25
for(int i=0;i<9;i++){
QLabel *label = new QLabel(&fenster);
label->setFrameStyle(QFrame::Panel | QFrame::Sunken);
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:


QLabel *label = new QLabel(&fenster);

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)


label->setGeometry(10*i,80,120,50);

Based on this I guess you are not using layouts, while you probably should.

yop
20th January 2006, 21:54
This will more or less work, but two more potential errors are here:

QLabel *label = new QLabel(&fenster);
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:

QLabel *label = new QLabel(fenster);

phil_
21st January 2006, 14:16
Thank you very much, you were a great help!