3

I'm having an issue with inserting items from existing list to combo-box, here is my code:

    #retrieving data:
    cursor = self.__db.cursor()        
    cursor.execute("select * from some_table")

    #creating a list:
    row = cursor.fetchone()        
    list = gtk.ListStore(str)
    list.append([row[0]])
    all_rows = cursor.fetchall()
    for row in all_rows:
        i = i + 1
        list.append([row[0]])

    #creating combo-box:
    self.combo_software = gtk.combo_box_entry_new_text()
    for name in list:
        self.combo_software.append_text(name[0])

Well, its works fine but two last lines are completely not efficient.

How can i insert all those items with more quick way?

Many thanks

Simon Feltman
  • 1,120
  • 7
  • 8
Eli
  • 4,576
  • 1
  • 27
  • 39

1 Answers1

3

You can bind combo boxes to a List/TreeModel directly. To do this, you need to setup a CellRenderer and bind its "text" attribute to a column in the model. By doing this, updates to the model are automatically reflected in the view:

import gtk

model = gtk.ListStore(str)
data = [['test ' + str(i)] for i in range(10)]

for row in data:
    model.append([row[0]])

cell = gtk.CellRendererText()
combo = gtk.ComboBox(model=model)
combo.pack_start(cell)
# Set the "text" attribute of CellRendererText to pull from column 0 of the model
combo.set_attributes(cell, text=0)

w = gtk.Window()
w.add(combo)
w.show_all()

gtk.mainloop()

This may also be useful: http://www.pygtk.org/pygtk2tutorial/sec-CellRenderers.html

As a side note, it is probably not a good idea to mask builtin Python types like "list" because it can cause strange bugs later in code:

list = gtk.ListStore(str)
...
# convert an iterable using the "list" builtin will now break later in code.
another_list = list(some_iterable)
TypeError: 'gtk.ListStore' object is not callable
Simon Feltman
  • 1,120
  • 7
  • 8
  • Thanks! it is faster from my solution, but still vary slow with 10k lines (and i have almost 100k lines..) – Eli May 21 '14 at 07:27
  • Another issue, try to add 100 lines for your example - why there are a blank spaces in the combo-box list? – Eli May 21 '14 at 07:50
  • @Eli: I'm not seeing blank spaces... is this a style thing (spacing between items) or an actual problem with the display of items? In terms of getting better performance, I'm not sure there is much that can be done with 10k or more rows beyond creating your own "virtualizing" custom control for large data sets. A combo box might not be the right widget for that amount of data in terms of usability anyhow. – Simon Feltman May 22 '14 at 02:51