Saturday, February 3, 2007

Populating a ComboBox

I'm using Glade to design my UI, which introduced some difficulty in figuring out how to populate my ComboBox (of which there are 2 versions in PyGTK). The PyGTK Tutorial was helpful, and the PyGTK IRC Channel took me the last mile.

The short of it is, a ComboBox works like a TreeView:

# create a store
weapon_store=gtk.ListStore(gobject.TYPE_STRING)
# populate the store
for w in weapon_names:
row=weapon_store.insert_after(None, None)
weapon_store.set_value(row, 0, w)
# get the Glade widget
left_hand_weapon_cbo=self.widgets.get_widget('leftHandWeapon')
left_hand_weapon_cbo.set_model(weapon_store)
# the business bit
cell=gtk.CellRendererText()
left_hand_weapon_cbo.pack_start(cell)
left_hand_weapon_cbo.add_attribute(cell, 'text', 0)
left_hand_weapon_cbo.set_wrap_width(3)


It would be nice if the Glade/PyGTK infrastructure would do more of the work of setting up the widgets with sensible defaults.

4 comments:

Michael R. Head said...

What was wrong with the basic combobox (really, a drop down) usage? http://www.pygtk.org/pygtk2tutorial/examples/comboboxbasic.py

Michael R. Head said...

oh, I see, it's because of the way glade creates the combobox...

Michael R. Head said...

Yeah, so with glade it's easy to populate things with static text, but it is definitely harder when the text needs to be dynamic. It does seem like there should be a way in glade to to select the type of list store you're using which would probably cut the number of lines of code in half.

Michael R. Head said...

One more comment, in glade-3, you can set your combobox model, which seems to solve the problem.