How to manipulate main window widgets through a signal function ( C and GTK+)?


I have very little experience and am coding a program for a college assignment.

I'm using the GTK+ 2.0 library. There are several widgets in the main window, among them a button that I connected to a function.

The problem is that I would like this function (connected to the button) to change the widgets in the main window.

For example: When I click on the button, it calls its function, and it writes a string obtained from an entry (text box in the main window) in a text widget (text display screen, also in the main window).

But in gtk, we don't call the signal function directly (it is through g_signal_connect(…)), so I don't know how to pass parameters or receive returns…

How can I get around this?


You can define your widgets in a structure and call them from within the function you created — including organizing your application — but calling g_signal_connect() , and then connecting one widget to another. A code example in which the text of an entry is put into a label after a button is clicked:

#include <gtk/gtk.h>

typedef struct MinhaJanela {

    GtkWidget *window;
    GtkWidget *botao;
    GtkWidget *texto;
    GtkWidget *label;
    GtkWidget *fixed;

} JanelaPrincipal;

static void botao_clicado(GtkWidget *, gpointer);

int main(int argc, char *argv[])
    JanelaPrincipal janela;

    gtk_init(&argc, &argv);

    janela.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

    gtk_window_set_title(GTK_WINDOW(janela.window), "Minha Janela");
    gtk_window_set_default_size(GTK_WINDOW(janela.window), 300, 80);
    gtk_window_set_position(GTK_WINDOW(janela.window), GTK_WIN_POS_CENTER);

    janela.fixed = gtk_fixed_new();
    gtk_container_add(GTK_CONTAINER(janela.window), janela.fixed);

    janela.texto = gtk_entry_new();
    gtk_fixed_put(GTK_FIXED(janela.fixed), janela.texto, 15, 15);
    gtk_widget_set_size_request(janela.texto, 90, 30);

    janela.botao = gtk_button_new_with_label("Botão");
    gtk_fixed_put(GTK_FIXED(janela.fixed), janela.botao, 115, 15);
    gtk_widget_set_size_request(janela.botao, 80, 30);

    janela.label = gtk_label_new("Label");
    gtk_fixed_put(GTK_FIXED(janela.fixed), janela.label, 190, 15);
    gtk_widget_set_size_request(janela.label, 100, 30);

    /* Sinais */
    g_signal_connect(GTK_OBJECT(janela.botao), (gpointer) "clicked", 
        G_CALLBACK(botao_clicado), &janela);

    g_signal_connect_swapped(G_OBJECT(janela.window), "destroy", 
        G_CALLBACK(gtk_main_quit), NULL);


    return 0;

/* Função chamada */
static void botao_clicado(GtkWidget *widget, gpointer data)
    gtk_label_set_text( GTK_LABEL( ((JanelaPrincipal *)data) -> label ),
                (gchar *)gtk_entry_get_text(GTK_ENTRY( ((JanelaPrincipal *)data)  -> texto)) );

Analyze the botao_clicado() and g_signal_connect() , it is between them that the widgets "communicate".

Scroll to Top