import gtk

class test_combo_box:

    # =======================================================
    def __init__(self):

        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_size_request(200,100)
        self.window.connect('delete_event', self.close_application)

        self.mycombo = gtk.ComboBox()

        context = [str(i) for i in range(150)]
#        context[1] = '-'
        self.set_model_from_list(self.mycombo, context, 10, 7)
        self.mycombo.set_row_separator_func(lambda model,i: model[i][1])
        self.window.add(self.mycombo)

        self.window.show_all()

    # =======================================================
    def set_model_from_list (self, combo, items, row_no=None, wrap_width_max=1):
        """Creates a model from a list of strings and connects it to a combobox"""

        model = gtk.ListStore(str,bool,int)
        combo_list = [[]]
        for i in items:
            if i is '-': #separator line
                if combo_list[-1] == []:
                    del combo_list[-1]
                combo_list.append(['-'])
            else:
                if combo_list[-1] == ['-']:
                    combo_list.append([])
                combo_list[-1].append(i)

        max_grp_size = max([len(elm) for elm in combo_list])
        if not row_no:
            row_no = max_grp_size
        col_no = min( 1 + (max_grp_size - 1) / row_no, wrap_width_max)
        cnt_list = []
        for grp in combo_list:
            grp_size = len(grp)
            wrap_height = max(row_no, 1 + (grp_size-1) / col_no)
            wrap_height = min(wrap_height, grp_size)
            for i in range(wrap_height):
                cnt = 0
                for elm in grp[i::wrap_height]:
                    model.append([elm, False, 1])
                    if elm is '-': #separator line
                        model[-1][1] = True
                    cnt += 1
                    cnt_list.append(cnt)
                model[-1][2] = col_no - cnt + 1

        combo.set_model(model)
        cell = gtk.CellRendererText()
        combo.pack_start(cell, True)
        combo.add_attribute(cell, 'text', 0)
        combo.set_column_span_column(2)
        combo.set_wrap_width(col_no)

    # =======================================================
    def close_application(self, widget, event=None, data=None):
        """Termination"""

        if gtk.main_level():
            gtk.main_quit()
        else:
            sys.exit(0)
        return False


if __name__ == '__main__':
    test_combo_box()
    gtk.main()
