views:

79

answers:

1

The following PyGTk code, gives a combo-box without an active item. This serves a case where we do not want to have a default, and force the user to select.

Still, is there a way to have the empty combo-bar show something like: "Select an item..." without adding a dummy item?

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)
A: 

Huge hack ahead (I just added this to your program):

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)

Don't see a nicer way.

doublep