How do I add items to a gtk.ComboBox created through glade at runtime?

12,360

Solution 1

Or you could just create and insert the combo box yourself using gtk.combo_box_new_text(). Then you'll be able to use gtk shortcuts to append, insert, prepend and remove text.

combo = gtk.combo_box_new_text()
combo.append_text('hello')
combo.append_text('world')
combo.set_active(0)

box = builder.get_object('some-box')
box.pack_start(combo, False, False)

Solution 2

Hey, I actually get to answer my own question!

You have to add gtk.CellRendererText into there for it to actually render:

self.iface_list_store = gtk.ListStore(gobject.TYPE_STRING)
self.iface_list_store.append(["hello, "])
self.iface_list_store.append(["world."])
self.tracked_interface.set_model(self.iface_list_store)
self.tracked_interface.set_active(0)
# And here's the new stuff:
cell = gtk.CellRendererText()
self.tracked_interface.pack_start(cell, True)
self.tracked_interface.add_attribute(cell, "text", 0)

Retrieved from, of course, the PyGTK FAQ.

Corrected example thanks to Joe McBride

Share:
12,360
Tom Duckering
Author by

Tom Duckering

Programmer and wearer of many hats.

Updated on June 04, 2022

Comments

  • Tom Duckering
    Tom Duckering almost 2 years

    I'm using Glade 3 to create a GtkBuilder file for a PyGTK app I'm working on. It's for managing bandwidth, so I have a gtk.ComboBox for selecting the network interface to track.

    How do I add strings to the ComboBox at runtime? This is what I have so far:

    self.tracked_interface = builder.get_object("tracked_interface")
    
    self.iface_list_store = gtk.ListStore(gobject.TYPE_STRING)
    self.iface_list_store.append(["hello, "])
    self.iface_list_store.append(["world."])
    self.tracked_interface.set_model(self.iface_list_store)
    self.tracked_interface.set_active(0)
    

    But the ComboBox remains empty. I tried RTFM'ing, but just came away more confused, if anything.

    Cheers.

  • OmarL
    OmarL almost 5 years
    It may be worth pointing out that the last parameter of add_attribute is the column from the ListStore that you want to display. In your case 0 is the right choice, but I needed 1 because I wanted to display the string from a Gtk.ListStore(int, str).