PDA

View Full Version : How to programatically form QLineEdit() object names?



scot_hansen
11th September 2010, 17:31
I am writting a GUI program using Python 2.7 and PyQt on Windows. My program reads parameter values from xml files and displays them allowing the user to change them on a GUI screen. The parameter names and the file where they are stored at are in a configuration xml file that I created by hand.

The program displays roughly 50 values on the screen. To display the initial values of the parameters once they are read in from the data files, I need 50 lines of code to display the values:

ui.txtBox1.setText(value1)
ui.txtBox2.setText(value2)
..........
ui.txtBox50.setText(value50)

I have a class for the form, winForm generated by QT designer. In the main Python code file, ui is the object created from the winForm class (ui = winForm()).

Is there a way to programatically form these text box commands to set the text so I don't need 50 lines of code?

In the configuration xml file that I created that is used by the program, I store the text box name for the variable. For example:

<boxName>ui.txtBox1</boxName>

I created an object, VarObject from a custom class that stores the boxName and the initial value of the parameter.

I then use the box name like this to set the text box value:
boxName.setText(value)

and get the error: boxName doesn't have a setText() attribute or member

I have also tried to store the text box names in a list and dictionary:

list = [ui.txtBox1, ui.txtBox2 ........]
dict = { "key1":uitxtBox1, "key2":uitxtBox2, ......}

Then I use list[0].setText(value)

That doesn't work either. I prefer to store the text box names in my configuration xml file so I don't have to modify the Python code.

Thank you for your help.

norobro
11th September 2010, 20:07
The reason that your code is not working is that you need the pointers to the objects in the form. Try something like this (in C++ -don't know Python):
QHash<QString, QLineEdit *> hash;
QList<QLineEdit *>lineEditNames = findChildren<QLineEdit *>();
foreach(QLineEdit *lineEditPtr, lineEditNames)
hash[lineEditPtr->objectName()]=lineEditPtr;

hash.value(txtBox1)->setText(value); // put this in the loop where you read from your xml file
QMap can also be used, but the docs say that QHash performs faster lookups.

Note: you will need to remove the "ui." from your object names.
HTH

scot_hansen
12th September 2010, 19:01
Thank you for the suggestion. I have several years of C++ experience and should be able to modify your code to work in Python. I feel the Python code will be a little shorter.