Question

Following some PyGTK tutorials, I'm trying to fill a combo box in gjs (native javascript on the Gnome desktop)

So far I came up with two similar ways that both almost work.

The first one is probably closest to the example in the tutorial:

var testStore = new Gtk.ListStore ();
testStore.append ([0, "test1"]);
testStore.append ([1, "test2"]);

var cbox = Gtk.ComboBox.new_with_model (testStore);
cbox.set_entry_text_column (1);
cbox.show ();

Main problem here is that it doesn't display anything, eg the combobox is empty. According to the tutorial, the "new Gtk.ListStore" needs the column types as arguments, but anything I put there just caused some error messages.

Mixing it with codes from the other examples, I came up with this one:

var testStore = new Gtk.ListStore ();
testStore.append ([0, "test1"]);
testStore.append ([1, "test2"]);

var cbox = Gtk.ComboBox.new_with_model (testStore);
var cellRenderer = new Gtk.CellRendererText ();

cbox.pack_start (cellRenderer, true);
cbox.add_attribute (cellRenderer, "text", 1);
cbox.show ();

It has the advantage that it acutally displays something, eg the combobox is filled with list items that can be selected - but they're all empty. Just blocks of white in white.

Any ideas?

Was it helpful?

Solution

Maybe redundant, but works:

let model = new Gtk.ListStore();
model.set_column_types([GObject.TYPE_STRING, GObject.TYPE_STRING]);

let cbox = new Gtk.ComboBox({model: model});
let renderer = new Gtk.CellRendererText();
cbox.pack_start(renderer, true);
cbox.add_attribute(renderer, 'text', 1);

model.set(model.append(), [0, 1], ['key1', 'value1']);
model.set(model.append(), [0, 1], ['key2', 'value2']);

cbox.set_active(0); // set value

cbox.connect('changed', function(entry) {
    let [success, iter] = cbox.get_active_iter();
    if (!success)
        return;
    let myValue = model.get_value(iter, 0); // get value
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top