Associate Data with Object or Widget
- From: author <millward Ms UManitoba CA>
- To: gtk-app-devel-list gnome org
- Subject: Associate Data with Object or Widget
- Date: Tue, 16 Oct 2001 15:42:16 -0500
I need some constructive critcism.
The subject is moving data from main() into a callback.
In this case, when a button is pressed, the contents
of a label changes and is also displayed on the command line.
This code works, but
I doubt that its an 'elegent solution'. For one thing, I
have to duplicate the data structure inside the callback.
And for another, all the data I want the callback to get
has to fit into a structure. Suppose there's something
that the callback needs that I can't stuff into the structure?
I never use global variables unless there is no choice.
Anyway, could someone take a look at this and tell
me a better way to write it? I'm just learnig GTK and I
don't want to get into bad habits.
*/
Associating Client Data with an Object or Widget
*/
#include <stdlib.h> /* malloc */
#include <gtk/gtk.h>
void callback(GtkWidget * widget, gpointer data);
int main(int argc, char * argv[] )
{
GtkWidget * window;
GtkWidget * button1;
GtkWidget * vbox;
typedef struct paxx
{
char * arry[6][20];
int number_of_strings; /* number of strings */
GtkWidget * labelx;
} ImageData;
ImageData * mydata = (ImageData *)malloc( sizeof(ImageData) );
mydata->number_of_strings = 6;
mydata->arry[0][0] = "Yesterday";
mydata->arry[1][0] = "Today";
mydata->arry[2][0] = "Tomorrow";
mydata->arry[3][0] = "Today + 2";
mydata->arry[4][0] = "Today + 3";
mydata->arry[5][0] = "Today + 4";
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_signal_connect(GTK_OBJECT(window), "delete_event",
GTK_SIGNAL_FUNC(gtk_main_quit),
NULL );
vbox = gtk_vbox_new(FALSE, 0);
mydata->labelx = gtk_label_new("New Label");
gtk_container_add(GTK_CONTAINER(vbox), mydata->labelx );
button1 = gtk_button_new_with_label("Change Label");
gtk_signal_connect(GTK_OBJECT(button1), "clicked",
GTK_SIGNAL_FUNC(callback),
(gpointer) mydata );
gtk_container_add(GTK_CONTAINER(vbox), button1);
gtk_container_add(GTK_CONTAINER(window), vbox );
gtk_widget_show_all(window);
gtk_object_set_data(GTK_OBJECT(button1), "image_data",
(gpointer) mydata);
gtk_main();
return 0;
}
void callback(GtkWidget * button1, gpointer data)
{
typedef struct Thiss
{
char * arry[6][20];
int buf_size;
GtkWidget * label;
} ARP;
ARP * zuma;
static int i = 0;
zuma = gtk_object_get_data(GTK_OBJECT(button1),
"image_data");
g_print("\n buf_size = %d\n", zuma->buf_size );
if( i >= (zuma->buf_size) )
i = 0;
g_print("\n arry[%d] = %s \n", i, zuma->arry[i][0] );
gtk_label_set_text(GTK_LABEL(zuma->label), zuma->arry[i++][0] );
}
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]