variable as object
Solved
General and Desktop
-
for (int i =1 ;i<5;i++) { QString s = QString::number(i); ui->("modra"+s)->setAutoDefault(false); ui->("modra"+s)->setIcon(QPixmap::fromImage(image)); ui->("modra"+s)->setIconSize(image.rect().size()); ui->("modra"+s)->resize(image.size()); }
I have buttons modra1-modra4. Image image is defined. Is that any way to use i from for cycle to change corresponding button properities?
Thanks
rktech -
You can search for objects by the object name: QObject::findChild()
-
What @Christian-Ehrlicher said is right. Your example code using it would look like this:
for (int i =1 ;i<5;i++) { QString name = "modra" + QString::number(i); QPushButton* button = findChild<QPushButton*>(name); button->setAutoDefault(false); button->setIcon(QPixmap::fromImage(image)); button->setIconSize(image.rect().size()); button->resize(image.size()); }
-
huh!? what's wrong with arrays of objects instead of discrete names for each indexed button?
Vector<QPushbutton*> buttonVector(5, nullptr); // 5 element container for (auto& i: buttonVector) { // c++17; access to each element i = new QPushButton; } // at this point you have a vector of QPushbutton* that are // each initialized with a QPushbutton // direct access by index // arguably more efficient than searching by char-array name buttonVector[3]->setIcon(image.rect().size()); buttonVector[1]->resize(image.size);
-
I think, that this is not what I asked. I need a way to create ui->modra1->... if i == 1 and ui->modra2->... if i == 2 ...
@rktech said in variable as object:
I need a way to create ui->modra1->... if i == 1 and ui->modra2->... if i == 2
This is not possible in C/C++ - variable names are compile time.