PDA

View Full Version : Access variable using its name as QString



homerun4711
22nd December 2010, 07:21
Hello!

As I wrote yesterday in another post, I have to read QStrings from many QLineEdits.
The answer was that this is best accomplished through a class using a QList of QLineEdits. But I have to set the names of all lineedits somehow.

Is it possible to access the variables through their QString'ed name?

Is something like that possible:


QLineEdit lineedit_1
QLineEdit lineedit_2
QLineEdit lineedit_3
...

QString lineedit1, lineedit2, lineedit3

QStringList lineedits
lineedits << "lineedit1" << "lineedit2" << "lineedit3".....

while (lineedits.hasNext)
{
PseudoCode: lineedits[INDEX] = SameNamedQLineEdit_[INDEX].text();
}

Well somehow my feeling points to "not possible, find another solution" :)
Kind regards,
HomeR

squidge
22nd December 2010, 07:48
I would instead have an array of QLineEdit's and reference them through that array. If you use QMap to store them, you can use the key as the name and the value as the pointer to the QLineEdit, so then you can reference them via a string rather than a numerical index (as QMap overrides operator [])

Lykurg
22nd December 2010, 09:02
It's a dangerous reply, so first:

Don't use my suggestion! Try what squidge said.

But theoretical you could use QObject::findChild().

homerun4711
22nd December 2010, 09:11
Thank you for your suggestions. They sound very good!
Kind regards,
HomeR