2

I created 9 QPushButtons which objectName's are E1, E2, E3, ..., E9. Now, I want to update their text field with strings I get from a database, so I want to do something like this:

query="SELECT evento FROM eventos;"
cur.execute(query)

i=1
for fetch in cur:
    evento=str(fetch)
    objectname="E"+str(i)
    self.objectname.setText(evento)
    i+=1

This loops fetches 9 lines (9 strings) and updates the buttons' display text. The problem is that I have to tell it which button to update and I can't figure out how to do it dynamically since the lines: objectname="E"+str(i) and self.objectname.setText(evento) won't work because AtributeError: 'MyWindowClass' object has no attribute 'objectname'

Mark Skelton
  • 3,663
  • 4
  • 27
  • 47
Diogo Magalhães
  • 441
  • 1
  • 9
  • 19
  • 1
    You want `getattr()` – kindall Mar 17 '16 at 20:07
  • Is this a duplicate of: [How to find an object by name in pyqt?](http://stackoverflow.com/questions/19048657/how-to-find-an-object-by-name-in-pyqt) You want to lookup objects depending on the *Qt name* you have set in their `objectName` property? – Bakuriu Mar 17 '16 at 20:09
  • Yes germn! It works perfectly! Thank you so much! I could kiss you right now! Didn't know about this gettattr() function. – Diogo Magalhães Mar 17 '16 at 20:10
  • @DiogoMagalhães you're welcome :) Feel free to accept answer. http://meta.stackexchange.com/a/5235 – Mikhail Gerasimov Mar 17 '16 at 20:14

2 Answers2

2

Use getattr():

getattr(self, "E"+str(i)).setText(evento)
Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159
0

You can also use

self.findChild(QtGui.QPushButton, 'E{0}'.format(i)).setText(evento)
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118