在gtk c中的对话框中打印输入框的值

时间:2017-07-09 13:51:07

标签: c gtk

我最近用c语言的gtk +工作过。

我尝试在对话框中的两个回调之间进行通信,而不是在主窗口like here)中进行通信。但是,与链接中的解决方案不同,程序会崩溃(当我尝试使用从参数中获取的小部件时,在第二次回调中)。

这是我的代码:

#include <gtk/gtk.h>
#include <stdlib.h>
#include <stdio.h>

static void print_text (GtkWidget *widget, gpointer data)
{
    GtkEntry* entry = data;
    printf("%s", gtk_entry_get_text(entry));
}

static void open_dialog (GtkWidget *widget, gpointer data)
{
    GtkWidget *window = data;
    GtkWidget *dialog;
    GtkWidget *content_area;
    GtkWidget *grid;
    GtkWidget *label;
    GtkWidget *button;
    static GtkEntry *textbox;

    dialog = gtk_dialog_new_with_buttons ("Get Text",
                                          window,
                                          GTK_DIALOG_MODAL,
                                          GTK_STOCK_OK,
                                          GTK_RESPONSE_OK,
                                          NULL);
    content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog));
    grid = gtk_grid_new();
    gtk_container_add (GTK_CONTAINER (content_area), grid);

    label = gtk_label_new("Value: ");
    gtk_grid_attach(GTK_GRID(grid), label, 0, 0, 1, 1);
    textbox = gtk_entry_new();
    gtk_entry_set_text(textbox, "<Value>");
    gtk_grid_attach(GTK_GRID(grid), textbox, 1, 0, 1, 1);

    gtk_widget_show_all (dialog);
    g_signal_connect (GTK_DIALOG (dialog), "response", G_CALLBACK (print_text), textbox);
}

static void activate (GtkApplication *app, gpointer user_data)
{
    GtkWidget *window;
    GtkWidget *button;
    GtkWidget *entry;
    GtkWidget *grid;

    window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Window");
    gtk_container_set_border_width (GTK_CONTAINER (window), 10);

    grid = gtk_grid_new ();
    gtk_container_add (GTK_CONTAINER (window), grid);

    button = gtk_button_new_with_label ("Print Text");
    g_signal_connect (button, "clicked", G_CALLBACK (open_dialog), window);
    gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 1, 1);

    gtk_widget_show_all (window);
}

int main (int argc, char **argv)
{
    GtkApplication *app;
    int status;

    app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}

程序应该在关闭对话框后打印对话框中的输入框的值。注意:在主窗口中有一个用于打开对话框的按钮。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

问题出在print_text函数上。 GtkDialog response signal的原型是:

  

void user_function(GtkDialog *对话框,                  gint response_id,                  gpointer user_data)

所以你必须将你的功能改为:

static void print_text (GtkWidget *widget, gint response_id, gpointer data)
{
    GtkEntry* entry = data;
    printf("%s", gtk_entry_get_text(entry));
    gtk_widget_destroy (widget); // This will close the dialog
}