[GTK4 C] GtkFileDialog seems to not use filter

I’m currently changing deprecated code in my GTK4 C app, and while changing GtkFileChooser to GtkFileDialog (which is way easier to use), the only thing I’m missing is the filter that apparently does nothing. The file dialog at runtime has no extension list. Maybe isn’t it implemented for the moment on Windows ?

my code

  dialog = gtk_file_dialog_new();
  gtk_file_dialog_set_title(dialog, "Ouvre fichier .OBJ");
  gtk_file_dialog_open(dialog, GTK_WINDOW(d->win), NULL, NULL, on_open_response, data);

  GtkFileFilter* filtre = gtk_file_filter_new();
  gtk_file_filter_add_suffix(filtre, "obj");
  gtk_file_filter_set_name(filtre, "OBJ Wavefront");
  GtkFilterListModel* lf = gtk_filter_list_model_new(NULL, filtre);
  gtk_file_dialog_set_filters(dialog, lf);
  gtk_file_dialog_set_current_filter(dialog, gtk_filter_list_model_get_filter(lf));

I’m continuing the coding on Linux (it’s nice that the code changed on Windows works on Linux even if I needed to update my GTK4 to latest version to have access to new widgets replacing deprecated ones). And it gives some hints to see what I’m doing wrong. I have a warning saying that gtk_file_dialog_set_filters expects a “GListModel *” and I’m giving it a “GtkFilterListModel *”. I tried to cast it but it doesn’t work like that.

You do not use a GtkFilterListModel for file filters: that’s a list model the filters its contents.

If you want to add filters to a file dialog, use a GListStore:

  g_autoptr (GListModel) filters = g_list_store_new (GTK_TYPE_FILE_FILTER);

  g_autoptr (GtkFileFilter) filter = NULL;

  // All files
  filter = gtk_file_filter_new ();
  gtk_file_filter_add_pattern (filter, "*");
  gtk_file_filter_set_name (filter, "All Files");
  g_list_store_append (filters, filter);

  // Image files
  filter = gtk_file_filter_new ();
  gtk_file_filter_add_mime_type (filter, "image/*");
  gtk_file_filter_set_name (filter, "Images");
  g_list_store_append (filters, filter);

  // Video files
  filter = gtk_file_filter_new ();
  gtk_file_filter_add_mime_type (filter, "video/*");
  gtk_file_filter_set_name (filter, "Video");
  g_list_store_append (filters, filter);

  gtk_file_dialog_set_filters (dialog, G_LIST_MODEL (filters));

Thanks a lot. Very nice, it works, only needed to change the beginning to g_autoptr (GListStore) filters …

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.