When you have similar buttons in the QPushButton class, is it a way I can put them in an array?
-
Hi Qt Programmers,
When I was designing a calculator, I had buttons from 0 - 9 just for the digits alone. I was thinking that is has to be a more efficient way than just copying and pasting those buttons 10 times to create those objects. It has to be a way that I can use a for-loop or something?
Can I get some tips? :)Thanks so much!!
-
Wel... yes, you can use a for loop:
for(int i=0; i < 10; ++i) yourLayout->addWidget(new QPushButton(QString::number(i)));
-
To add something to @Chris-Kawa I think in your case could be also useful to use QSignalMapper
-
Thanks Chris for the reply!! That works, but it doesn't give 10 different names to the objects. What I mean is:
QPushButton button1 = new QPushButton():
QPushButton button2 = new QPushButton()
:QPushButton button3 = new QPushButton():.......
So basically objects button1, button2, and button3 that I can simply call and do some things with.
If only this was legal.
for(int x = 0, x < 10; x++) {
= new QPushButton(QSring::number(x))
}that way I can have button[0], button[1], button[2], and so on and so.
-
The is nothing illegal about that for-loop, except that you need
to have array of QPushButton pointers, and QString is misspelled. -
Thanks!!! Yeah, you right. It wasn't misspelled when I first tried it. I will see what I can do to establish an array of QPushButton pointers.
-
QList<QPushButton*> buttons; for(int x = 0; x < 10; ++x) buttons << new QPushButton(QString::number(x));