Enable GtkFileChooserDialog to select files OR fol

2019-02-25 12:48发布

问题:

Using GTK+'s GtkFileChooserDialog, how can I allow the user to select a file or a folder (both are valid here). The actions available are mutually exclusive.

回答1:

Unfortunately I don't think this is possible.

I played around with this a bit in the "create a torrent" dialog in Transmission, and wound up using a radibox to enable one of two chooserdialogbuttons, one in file mode and the other in folder mode.



回答2:

You could add another button. Here is a small example which illustrates how you could do it.

void filechooser(GtkWidget* widget, gpointer data) {
   // we will pass the filepath by reference
   string* filepath = (string*) data;
   GtkWidget *dialog = gtk_file_chooser_dialog_new(
         "Open File", NULL, 
         GTK_FILE_CHOOSER_ACTION_OPEN,
         GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
   // add a button which allows the user to select a folder
   const guint selected = 0; // response from the button
   gtk_dialog_add_button(GTK_DIALOG(dialog),"Select",selected);
   // get the path the user selected
   guint response = gtk_dialog_run(GTK_DIALOG(dialog));
   if(response == GTK_RESPONSE_ACCEPT || response == selected){
      *filepath = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
   }
   gtk_widget_destroy(dialog);
}

Note that the "Select" button in my example does the same action as "Open" if a file is selected, it's only really different for folders.