简体   繁体   English

设置组合框(gtk)的条目

[英]set up the entry of a combobox (gtk)

How could I set up the text of a combobox without knowing its id? 如何在不知道组合框ID的情况下设置组合框的文本? I have a combobox populated with a list of name ('Jack','Emily','Paul',...). 我有一个组合框,上面有一个名称列表('Jack','Emily','Paul',...)。 By default, the combo is set on -1 but I want it to be set on "Paul". 默认情况下,组合设置为-1,但我希望将其设置为“ Paul”。

Here is my code to declare and populate the combo with tuple (id,fabName) : 这是我的代码,用元组(id,fabName)声明并填充组合:

    self.cmbFabricant = builder.get_object("cmbFabricant")
    self.cmbFabricant.set_model(lstStore)
    self.cmbFabricant.set_entry_text_column(1)

Now, I'd like to set the combobox on the item called "Paul". 现在,我想在名为“ Paul”的项目上设置组合框。 I thought I could write : 我以为我可以写:

    self.cmbFabricant.set_active_id('Paul')

I was wrong. 我错了。

I could be wrong, but I think set_active_id is new in GTK+ 3, and PyGTK is GTK+ 2. If you want to use GTK+ 3, you have to switch to PyGObject . 我可能错了,但是我认为set_active_id是GTK + 3中的新增功能,而PyGTK是GTK +2。如果要使用GTK + 3,则必须切换到PyGObject

But if you're stuck on PyGTK, you can easily work around it by doing something like this: 但是,如果您坚持使用PyGTK,则可以通过执行以下操作轻松解决此问题:

import gtk

def set_active_name(combobox, col, name):
    liststore = combobox.get_model()
    for i in xrange(len(liststore)):
        row = liststore[i]
        if row[col] == name:
            combobox.set_active(i)

window = gtk.Window()
window.connect("destroy", gtk.main_quit)

liststore = gtk.ListStore(int, str)
liststore.append([0, 'Jack'])
liststore.append([1, 'Emily'])
liststore.append([2, 'Paul'])

combobox = gtk.ComboBox()
cell = gtk.CellRendererText()
combobox.pack_start(cell)
combobox.add_attribute(cell, 'text', 1)
combobox.set_model(liststore)

set_active_name(combobox, 1, 'Paul')

window.add(combobox)
window.show_all()

gtk.main()

I'm not sure if there is a more elegant/efficient way, but this works at least. 我不确定是否有更优雅/有效的方法,但这至少有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM