如何设置Gtk.ComboBox的值?

我能想到的只是与ComboBox.GetEnumerator或类似的东西有关。

我想做的事情如下:

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; } } 

但是,这不起作用。

您的代码不起作用的原因是“combobox中的项目”实际上是用于显示数据列的单元格渲染器。 要获取实际数据,您需要TreeModel对象。

如果你真的必须根据组合中的内容进行选择,那么你可以这样做:

 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)); 

但是,通常将索引值保持为更简洁,如下所示:

 List values = new List(){"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); 

作为替代方案,如果您将ComboBox的元素存储在ArrayList则可以像这样设置“selected index”

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

我遇到了类似的问题,C#中的这个答案很有帮助,但C语言中的最终解决方案看起来非常不同。 我在这里发帖是因为它是谷歌搜索的第一个。

基本上,如果您正在查看GTK ComboBox并使用GTK树模型并希望获取信息,则必须使用iter模式。 其他语言(如Python和C#)的包装使它变得相当容易,但对于那些仍在使用C和GTK的人来说,这是解决方案:

假设你有一个扁平的gtkcombobox并且你只需要从中得到一些东西,你可以使用这样的东西来表示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's 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中存储更多信息,您可以使用以下内容获取更多信息:

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

希望有所帮助。