tags:

views:

186

answers:

3

Hi,

I'm trying to dynamically create buttons at runtime with PyQT4.7

However, this being my first python program I'm not sure how to get the functionality I want.

I would like to be able to substitute a text string for an attribute name:

i.e.

for each in xrange(4):
    myname = "tab1_button%s" % each  #tab1_button0, tab1_button1, tab1_button2

    #self.ui.tab1_button0 = QtGui.QPushButton(self.ui.tab) <--normal code to create a named button
     setattr(self.ui,myname,QtGui.QPushButton(self.ui.tab)) #rewrite of line above to dynamicly generate a button

#here's where I get stuck. this code isn't valid, but it shows what i want to do
     self.ui.gridLayout.addWidget(self.ui.%s) % myname
#I need to have %s be tab1_button1, tab1_button2, etc. I know the % is for string substituion but how can I substitute the dynamically generated attribute name into that statement?

I assume there's a basica language construct I'm missing that allows this. Since it's my first program, please take it easy on me ;)

+2  A: 

If I interpreted this correctly, I think what you want is this:

self.ui.gridLayout.addWidget(getattr(self.ui,myname))

Give that a go. In Python the following two statements are functionally equivalent (from the link below):

value = obj.attribute
value = getattr(obj, "attribute-name")

For extra context:

http://effbot.org/zone/python-getattr.htm

Brent Nash
A: 

Just assign the button to a variable so you can both set the attribute and add the widget.

for i in range(4):
    name = 'button%d' % i
    button = QtGui.QPushButton(...)
    setattr(self, name, button)
    self.ui.gridLayout.addWidget(button)

Personally I would add the buttons to a list instead of giving them different names.

FogleBird
in this scenario the buttons are getting numerically ordered names, but in the program i'm writing, their entire names will be pulled from a dictionary, so I'm not sure how I'd keep track of them without intelligent names with your example
PyNewbie27
Store the buttons in a dictionary?
FogleBird
A: 

I think you might benefit from knowledge of lists (commonly called arrays in other languages)

self.buttons = [None, None, None, None]
for each in xrange(4):
     self.buttons[each] = QtGui.QPushButton(self.ui.tab)
     self.ui.gridLayout.addWidget(self.buttons[each])

For a tutorial on Python lists: http://effbot.org/zone/python-list.htm

Wallacoloo