GTK & expat notes
I've just finished my senior project, which is a GTK program to display line chart, pie chart and some raw datas collected from a system status collector. It's part of the SkyEye project. It reads data from a XML document, so it's also used expat as XML parser.
The main reason I chose GTK and expat is that they are both written in plain C and can be used in a plain C program. I don't like C++ much.
Here's some notes.(I'm using GTK 1.x, not GTK 2)
- expat: expat is simple to use. First call XML_ParserCreate to create the parser and allocate memory, then call XML_SetElementHandler to mount handle functions. Here you can also us XML_SetUserData to point the data block of user data, which can avoid use of global variables. Then just read the xml file and feed into the parser use XML_Parse, and finally free it use XML_ParseFree.
- GTK overview: Use gtk_init to handle command line parameters, then create the main window, and the widgets of the main window, show it, and use gtk_main to start the message looping. Use gtk_main_quit to back to end the call of gtk_main.
- GTK tree: First create the main tree widget use gtk_tree_new, the the items use gtk_tree_item_new_with_label, and append the items into the tree use gtk_tree_append. To create subtrees, first use gtk_tree_new to create a tree, then use gtk_tree_item_set_subtree to set this tree a subtree of a tree item.
- GTK drawing area: A drawing area is used to draw a graph. Create a drawing area widget on to the window, and then use GDK functions to draw a graph on to it. There're 2 important signals: expose_event & configure_event. expose_event was trigged every time the drawing area is expose(in another word, showed out), and configure_event was trigged every time the drawing area is resized. You should handle this 2 signals to redraw the graph.
- GDK: GDK is the low-level drawing functions used by GTK. There are 2 important parameters for a gdk_draw_xxx function: pixmap & gc.
pixmap is the buffer. use the following statement to create a pixmap:pixmap = gdk_pixmap_new(d_area->window, d_area->allocation.width, d_area->allocation.height, -1);
gc = gdk_gc_new(d_area->window);
gdk_color_parse(rgbstring, &color);
gdk_colormap_alloc_color(gdk_colormap_get_system(), &color, FALSE, TRUE);
gdk_gc_set_foreground(gc, &color);
Once you've got pixmap and gc, you can use statement gdk_draw_xxx(pixmap, gc, ...) to draw something on to the pixmap, in which xxx can be line, arc, etc. Finally, usegdk_draw_pixmap( d_area->window, d_area->style->fg_gc[GTK_WIDGET_STATE(draw)], pixmap, 0, 0, 0, 0, draw->allocation.width, draw->allocation.height);