I am trying to use setattr on a UI element (QLineEdit) to fill in with what was read from a text file. I believe in order to set a QlineEdit it would be self.lineEdit.setText()
The text file I am reading consists of a Name and it's value:
Name1=Value1
splitLine[0] consists of "Name1", and splitLine[1] is "Value1". self.Name1 is the name of the lineEdit I am changing, hence I used eval() to pass the actual value "Name1" to setattr.
I am not sure how to go about setting the value. Right now I have tried these with no success:
setattr(self, eval("splitLine[0]"), eval("splitLine[1]"))
setattr(self, eval("splitLine[0]"), setText(eval("splitLine[1]")))
Also, using:
self.splitLine[0].setText(splitLine[1])
Does not work as it thinks the actual object is called splitLine, rather than it's value (hence why I tried eval() ).
# AttributeError: 'Ui_Dialog' object has no attribute 'splitLine'
You need to use getattr
, not setattr
. That is, you first need to get the line-edit object (via its attribute name), so that you can then call its setText
method to populate the field:
lineEdit = getattr(self, splitLine[0])
lineEdit.setText(splitLine[1])
or in one line:
getattr(self, splitLine[0]).setText(splitLine[1])