PDA

View Full Version : Can not create buttons with for loop



Ahmed Abdellatif
28th September 2017, 09:21
I tried to create a list of buttons using for loop as follow:

Mywidget::Mywidget()
{
QVBoxLayout *h_layout=new QVBoxLayout(this);
QPushButton *close_button=new QPushButton[4];
for (int i = 0; i < 5; ++i) {
close_button[i]=new QPushButton("Close",this);
h_layout->addWidget(close_button);
}
}
But the following error appears:

error: no match for 'operator=' (operand types are 'QPushButton' and 'QPushButton*')close_button[i]=new QPushButton("Close",this);
^
But if i removed
close_button[i] and make it only
close_button it create the required button, but the problem here that i can not use every pointer to do specific thing for example :

connect(close_button[2],SIGNAL(clicked(bool)),qApp,SLOT(quit()));
Please help

high_flyer
28th September 2017, 10:35
*sigh*
You really should first learn basic syntax and basic concepts of what is an array, and containers of C++.



Mywidget::Mywidget()
{
QVBoxLayout *h_layout=new QVBoxLayout(this);
for (int i = 0; i < 5; ++i) {
QPushButton* pButton = new QPushButton("Close",this);
h_layout->addWidget(pButton);
}
}

GeneCode
29th September 2017, 07:21
QPushButton *close_button=new QPushButton[4];

This is syntax error in code.

Normally you create a button like so:


QPushButton *pbtn = new QPushButton(this); // this is parent of the button
QPushButton *pbtn = new QPushButton("Title",this); // assigning title and parent

Both are single buttons. but if u want many buttons in array you can do something like:


QPushButton *btnArray[5];
for (i=0;i<5; i++) {
btnArray[i] = new QPushButton(this);
// maybe good to assign object name too
btnArray[i].objectName = "btn" + QString::number(i);
}

Ahmed Abdellatif
29th September 2017, 11:57
Thank you :)