我在将项目从现有列表插入组合框时遇到问题,这是我的代码:
#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])
嗯,它工作正常,但最后两行完全没有效率。
如何以更快的方式插入所有这些项目?
非常感谢
最佳答案
您可以将组合框直接绑定(bind)到 List/TreeModel。为此,您需要设置 CellRenderer 并将其“文本”属性绑定(bind)到模型中的列。通过这样做,对模型的更新会自动反射(reflect)在 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()
这也可能有用: http://www.pygtk.org/pygtk2tutorial/sec-CellRenderers.html
作为旁注,屏蔽内置 Python 类型(如“list”)可能不是一个好主意,因为它可能会在以后的代码中导致奇怪的错误:
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
关于 python GTK : How to insert items from list to combobox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23757738/