PDA

View Full Version : Can you use a pointer to take the place of an object name?



JustBobC
10th June 2016, 04:05
I need to change properties of a couple of hundred objects (mostly pushButtons) according to integer data. The code would look like this:

ui->pbN_20->setText(display_value);
ui->pbN_20->setStyleSheet("background-color: white");
ui->pbN_21->setStyleSheet("background-color: palegreen");

Having the integers 20 and 21, it takes an awful lot of switches and if else code to hook up with the code above.

It would be great if you could do something like:

int cellNumber = 20;
OName = "pbN_" + QString::number(cellNumber);
ui->OName->setText(display_value);

but a string is not a valid object name. So, is there some way of constructing a pointer to an object name that would accomplish this?

jefftee
10th June 2016, 05:01
Look at QObject::findChild

yeye_olive
10th June 2016, 13:22
Instead of using tons of variables (pbN_*) to store the pointers to the pushbuttons, you should put them all in a container such as a QVector.

anda_skoa
10th June 2016, 18:05
Instead of using tons of variables (pbN_*) to store the pointers to the pushbuttons, you should put them all in a container such as a QVector.

Indeed, or a hash/map if not all index values are used.

While jefftee's suggestion would also work, a suitable data structure is much cleaner than traversing the object tree every time such a change is required.

Cheers,
_