gpt4 book ai didi

c++ - GTK+ 3 native 文件选择器 - 允许的文件类型和默认文件名

转载 作者:搜寻专家 更新时间:2023-10-31 02:03:42 26 4
gpt4 key购买 nike

我正在使用 GTK+ 创建 C++ 程序。为了选择文件,我使用了 native 文件选择器,因为 gtk 文件选择器有内存泄漏。

这是我的问题:如何在 GTK+ 中为 native 文件选择器设置默认文件名(在保存时)以及如何为其设置文件过滤器 - 以便能够仅打开或保存特定的文件扩展名?

我的程序适用于 Win32。示例代码:

static void cb_SaveFileAs(GtkWidget *caller)
{
GtkWindow *parent_window = GTK_WINDOW(caller);
GtkFileChooserNative *native;
GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_SAVE;
gint res;

native = gtk_file_chooser_native_new("Save File",
parent_window,
action,
"_Save",
"_Cancel");

res = gtk_native_dialog_run(GTK_NATIVE_DIALOG(native));
if (res == GTK_RESPONSE_ACCEPT)
{
char *filename;
GtkFileChooser *chooser = GTK_FILE_CHOOSER(native);
filename = gtk_file_chooser_get_filename(chooser);

// save the file
save_to_file(filename);

g_free(filename);
}

g_object_unref(native);
}

最佳答案

下面是一个使用 *.cpp 模式设置 GtkFileFilter 以仅显示 C++ 文件的示例。它还将默认文档名称设置为 test.cpp

编译:g++ filechooser.cpp `pkg-config --cflags gtk+-3.0` `pkg-config --libs gtk+-3.0`

#include <gtk/gtk.h>

static void dialog_result(GtkWidget *dialog, gint resp, gpointer data)
{
if (resp == GTK_RESPONSE_OK) {
// do nothing
} else {
gtk_widget_destroy(dialog);
}
}

static void open_dialog(GtkWidget *button, gpointer window)
{
GtkWidget *dialog;
GtkFileFilter *filter;

dialog = gtk_file_chooser_dialog_new("Choose a file:", GTK_WINDOW(window),
GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_SAVE,
GTK_RESPONSE_OK, GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL, NULL);

filter = gtk_file_filter_new();
gtk_file_filter_add_pattern(filter, "*.cpp");
gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter);
gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), "test.cpp");
gtk_widget_show_all(dialog);
gint resp = gtk_dialog_run(GTK_DIALOG(dialog));
if (resp == GTK_RESPONSE_OK)
g_print("%s\n", gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)));
else
g_print("You pressed the cancel\n");
gtk_widget_destroy(dialog);
}

int main()
{
gtk_init(NULL, NULL);
GtkWidget *window, *button;
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window, "delete_event", G_CALLBACK(gtk_main_quit), NULL);
button = gtk_button_new_with_label("Save");
g_signal_connect(button, "clicked", G_CALLBACK(open_dialog), window);
gtk_container_set_border_width(GTK_CONTAINER(window), 100);
gtk_container_add(GTK_CONTAINER(window), button);
gtk_widget_show_all(window);
gtk_main();
}

关于c++ - GTK+ 3 native 文件选择器 - 允许的文件类型和默认文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54951379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com