How to set the value of Gtk.ComboBox?

All I can figure out is something in common with ComboBox.GetEnumerator or something like that.

I would like to do something like:

System.Collections.IEnumerator e = this.task_difficulty_combobox.GetEnumerator();
while (e.MoveNext())
{
    if (e.ToString() == this.task.Difficulty.ToString())
    {
        Gtk.TreeIter i = (Gtk.TreeIter)e.Current;
        this.task_difficulty_combobox.SetActiveIter(i);
        break;
    }
}

However, this does not work.

+3
source share
3 answers

The reason your code doesn't work is because the "elements in combobox" are actually cell handlers packed into it to display data columns. To get the actual data, you need a TreeModel object.

If you really have to choose based solely on what's in the combo, here's how you can do it:

string[] values = new string[]{"one", "two", "three"};
var combo = new ComboBox(values);

Gtk.TreeIter iter;
combo.Model.GetIterFirst (out iter);
do {
  GLib.Value thisRow = new GLib.Value ();
  combo.Model.GetValue (iter, 0, ref thisRow);
  if ((thisRow.Val as string).Equals("two")) {
    combo.SetActiveIter (iter);
    break;
  }
} while (combo.Model.IterNext (ref iter));

However, it is usually more concise so that your values ​​are indexed as follows:

List<string> values = new List<string>(){"one", "two", "three"};  
var combo = new ComboBox(values.ToArray());

// Select "two"
int row = values.IndexOf("two");
Gtk.TreeIter iter;
combo.Model.IterNthChild (out iter, row);
combo.SetActiveIter (iter);
+5
source

" " , ComboBox, Array List

for (int i = 0; i < combo.Model.IterNChildren(); ++i) //iterate over ComboBox elements
{
  if (myList[i].Equals(elementToSelect))
  {
    combo.Active = i;
    break;
  }
}
+1

, # , C -. , Google.

, GTK ComboBox GTK Tree Model, , iter . , Python #, , , C GTK, :

, gtk, - , - c:

int set_combo_box_text(GtkComboBox * box, char * txt) 
{
   GtkTreeIter iter;
   GtkListStore * list_store;
   int valid;
   int i;
   list_store = gtk_combo_box_get_model(box);

   // Go through model list and find the text that matches, then set it active
   i = 0; 
   valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL(list_store), &iter);
   while (valid) {
      gchar *item_text;
      gtk_tree_model_get (GTK_TREE_MODEL(list_store), &iter, 0, &item_text, -1); 
      printf("item_text: %s\n", item_text);
      if (strcmp(item_text, txt) == 0) { 
         gtk_combo_box_set_active(GTK_COMBO_BOX(box), i);
         return true;
         //break;
      }    
      i++; 
      valid = gtk_tree_model_iter_next (GTK_TREE_MODEL(list_store), &iter);
   }
   printf("failed to find the text in the entry list for the combo box\n");
}

combobox, iter, - :

valid = gtk_tree_model_get(GTK_TREE_MODEL(list_store), &iter, 0, &item_0, 1, &item_1, 2, &item_2, ... , -1); 

Hope this helps.

0
source

Source: https://habr.com/ru/post/1721529/


All Articles