没有活动项的gtk.ComboBox中的文本

时间:2010-05-16 21:41:28

标签: python combobox pygtk

以下PyGTk代码给出了一个没有活动项的组合框。 这适用于我们不希望有默认值的情况, 并强制用户选择。

仍然有办法让空的组合栏显示如下:    “选择一个项目......” 没有添加虚拟物品?

import gtk
import sys
say = sys.stdout.write

def cb_changed(w):
    say("Active index=%d\n" % w.get_active())

topwin = gtk.Window()
topwin.set_title("No Default")
topwin.set_size_request(0x100, 0x20)
topwin.connect('delete-event', gtk.main_quit)
vbox = gtk.VBox()

ls = gtk.ListStore(str, str)
combo = gtk.ComboBox(ls)
cell = gtk.CellRendererText()
combo.pack_start(cell)
combo.add_attribute(cell, 'text', 0)
combo.connect('changed', cb_changed)

ls.clear()
map(lambda i: ls.append(["Item-%d" % i, "Id%d" % i]), range(3))

vbox.pack_start(combo, padding=2)
topwin.add(vbox)
topwin.show_all()

gtk.main()
say("%s Exiting\n" % sys.argv[0])
sys.exit(0)

1 个答案:

答案 0 :(得分:0)

未来的巨大黑客攻击(我刚刚将其添加到您的程序中):

import gtk
import sys
say = sys.stdout.write

def cb_changed(w):
    say("Active index=%d\n" % w.get_active())

topwin = gtk.Window()
topwin.set_title("No Default")
topwin.set_size_request(0x100, 0x20)
topwin.connect('delete-event', gtk.main_quit)
vbox = gtk.VBox()

ls = gtk.ListStore(str, str)
combo = gtk.ComboBox(ls)
cell = gtk.CellRendererText()
combo.pack_start(cell)
combo.add_attribute(cell, 'text', 0)
combo.connect('changed', cb_changed)

#- Begin of the hack ----------------------------------
def special_empty_text (cell_view, event):
    if cell_view.window is None:
        return False

    row = cell_view.get_displayed_row ()
    if row is not None:
        return False

    layout   = cell_view.create_pango_layout ('bla bla bla')
    context  = cell_view.window.cairo_create ()

    xpad = 0
    ypad = 0

    renderer = cell_view.get_cells () [0]
    if renderer is not None:
        xpad = renderer.props.xpad
        ypad = renderer.props.ypad

    context.move_to (cell_view.allocation.x + xpad, cell_view.allocation.y + ypad)
    context.set_source_rgb (0.6, 0.6, 0.6)
    context.show_layout (layout)

    return True

combo.child.connect ('expose-event', special_empty_text)
#- End of the hack ----------------------------------

ls.clear()
map(lambda i: ls.append(["Item-%d" % i, "Id%d" % i]), range(3))

vbox.pack_start(combo, padding=2)
topwin.add(vbox)
topwin.show_all()

gtk.main()
say("%s Exiting\n" % sys.argv[0])
sys.exit(0)

看不到更好的方式。