Source: Internet
Author: User
Tags gtk locale setting automake

GTK + adopts a C language development framework with OO characteristics, which enables it to closely integrate with the operating system in the development of GUI applications, while at the same time being very simple, many of the code can be simply copied and changed. A Linux GUI program can be created with only one C source code file. The code running environment in this article is redhat7.2, and GTK + version is GTK + 2.1.2.

Helloworld written with GTK +

The following code is a helloworld routine compiled by the author using GTK +. After compilation, a window with a button is displayed. A prompt dialog box is displayed when you click the button.

// Hello. c
# Include <GTK/GTK. h>
// Callback function of the button in the Main Window
Voidon_button_clicked (gtkwidget * button, gpointer userdata)
Gtkwidget * dialog;
// Create a dialog box with the confirmation button. The parent control is empty.
Dialog = gtk_message_dialog_new (null,
Gtk_dialog_modal | gtk_dialog_destroy_with_parent,
Gtk_buttons_ OK,
(Gchar *) userdata );
Gtk_dialog_run (gtk_dialog (DIALOG); // display and run the dialog box
Gtk_widget_destroy (DIALOG); // The destroy dialog box.
// Main Function
Intmain (INT argc, char * argv [])
Gtkwidget * window, * button;
// Initialize the GTK + program
Gtk_init (& argc, & argv );
// Create a window and add a callback function for the window closing signal to exit
Window = gtk_window_new (gtk_window_toplevel );
G_signal_connect (g_object (window), "delete_event ",
G_callback (gtk_main_quit), null );
Gtk_window_set_title (gtk_window (window), "Hello world! ");
Gtk_container_set_border_width (gtk_container (window), 10 );
// Create a button control, add a callback function for the clicked signal, and put it in the window
Button = gtk_button_new_with_label ("Hello world! ");
G_signal_connect (g_object (button), "clicked ",
G_callback (on_button_clicked), (gpointer) "Hello! /N free world. ");
Gtk_container_add (gtk_container (window), button );
// The following function displays all the other widgets in the window control.
Gtk_widget_show_all (window );
Gtk_main ();
Return false;

You can directly use the command "GCC 'pkg-config-cflags-libs GTK + 2.0 'hello. C-O hello" to compile the above Code, but it is best to make a MAKEFILE file with the following content:

Cc = gcc
$ (CC) 'pkg-config -- cflags -- libs GTK +-2.0 'Hello. C-O hello

In this way, you can use the make command to compile the Code, which makes it much simpler and is not prone to errors. I emphasize the quotation marks again. Many beginners often make this mistake. ['] is [~]. The single quotation mark below, instead of [']; this involves command reference in Linux Shell programming. The standard bash in Linux supports command reference, other shells are not necessarily the same.

The following two figures show the running window of the program and the dialog box popped up by clicking the hello World button:






Initialization, main cycle, and exit

Unlike using C to develop GUI programs in MS Windows, GTK + does not use the winmain function. The standard format of the main function in C language is used directly, Which is consistent in the UNIX operating system family. The function gtk_init starts with the Peugeot GTK + program. Its two parameters are the addresses of the two parameters of the main function. After this function, you can process various related components of the program, such as the creation and display of the control, adding a callback function to the control signal, and setting or modifying the control attributes. Finally, execute the gtk_main function. The program enters the main event loop, receives signals, and calls the corresponding callback function for the signals. The function gtk_main_quit is used to end the main event loop, that is, exit the running of the GTK + program.

Control creation, display, and Layout

Controls in GTK + are divided into container controls and non-container controls 1. Non-container controls are mainly basic GUI elements, such as text labels, images, and text input controls. There are multiple container controls, in common, other controls can be discharged in a certain way. GTK + forms a unique GUI layout style. The GTK + control creation function is generally in the form of GTK _ control name_new (parameter ...) or GTK _ control name_new_with _ parameter name (parameter ...), its return value is a pointer of the gtkwidget type. After creation, you can call the gtk_widget_show function to display or hide the control, or use related functions to modify the properties of the control.

Signal connection and callback Functions

GTK + uses signals and callback functions to process events from outside. Controls inherit the same signal from their parent controls, and different controls have different signals, if the button control has a "clicked" signal, the text label control does not. GTK + 2.0 uses the macro g_signal_connect to connect the signal to the callback function, which is related to GTK + 1. the key difference of Version X is that the macro has four parameters. The first parameter is the object connecting the signal. In this example, the button or window must be converted using the g_object macro, convert the object type gtkwidget to the gobject type. The format is usually g_object (button), the second parameter is the signal name in string format, and the third parameter is the callback function name, use the g_callback macro for conversion. The fourth parameter is the pointer of the parameter to be passed to the callback function. In the above example, the callback function "on_button_clicked" is added to the "clicked" signal of the button ":

G_signal_connect (g_object (button), "clicked ",
G_callback (on_button_clicked), (gpointer) "Hello! /N free world. ");

Careful readers will immediately see a disadvantage of this macro, that is, they can only pass a parameter for the callback function. Of course, smart readers will immediately think of using the structure type to pass multiple parameters. The above content seems more complicated for beginners. As long as the threshold is reached, it actually enters the GTK + world.


Back to Top

International programming

Gettext package

The program running above is displayed in the main window in English. We can change it to Chinese, so that the single language version is not suitable for internationalization of the application. In GTK +, the gettext package is used to internationalize the application, this makes the problem very simple. The gettext package is an important tool for GNU engineering to solve international problems. The current version is 0.11.x and supports C/C ++ and Java languages. It is widely used in the open-source field, gnome/GTK + is used to solve international problems. In normal cases, the GNU/Linux system installs the software package by default.

Code Implementation

First, add the relevant C Language header file in the source code as follows:

# Include <libintl. h> // gettext support
# Include <locale. h> // supported by locale

Then define the Macro. the following definition form applies the standard format in GNOME/GTK +:

# Define package "hello" // package name
# Define localedir "./locale" // directory of locale
# DEFINE _ (string) gettext (string)
# Define N _ (string) String

Add the following functions to the main function of the program:

Bindtextdomain (package, localedir );
// The above functions are used to set the location of the international translation package.
Textdomain (Package );
// The above function is used to set the name of The International Translation package, omitting. Mo

Related string Modification

Rewrite the string that needs to be internationalized in the code-that is, the multi-language output string to the _ () Macro. The Code is as follows:

Gtk_window_set_title (gtk_window (window), _ ("Hello world! "));
Button = gtk_button_new_with_label (_ ("Hello world! "));
G_signal_connect (g_object (button), "clicked ",
G_callback (on_button_clicked), (gpointer) (_ ("hello, the free world! ")));

Generate relevant documents and Translation

After the preceding modification, run the following command: xgettext-K _-O hello. po hello. c. Its function is to set hello. the following line in C starts to enclose the string (as shown in the macro definition) in hello. in the Po file. You can add the software package name, version, and translator's email address to the header of the Po file. The comments starting with "#" in the Po file are as follows. the content of the Po file. The content after msgid is in English, and the content after msgstr is in the translated Chinese. After the translation is completed, it is saved in utf8 format.

#: Hello. C: 26 hello. C: 29
Msgid "Hello world! "
Msgstr "Hello world! "
#: Hello. C: 31
Msgid "hello, the free world! "
Msgstr "Hello, free world! "

Run the following command: msgfmt-O hello. po will be hello. the PO file is formatted as the file, so that the program can correctly read the data in the mo file according to the current locale setting during runtime, so as to display the information of the off-language. About. the location of the Mo file. This program is located in. /lc_messages directory under the Chinese directory zh_cn under the locale directory, that is. in the/locale/zh_cn/lc_messages directory, the default directory in RedHat is/usr/share/locale. Copy the mo file generated in this step to the corresponding directory, set locale to simplified Chinese, and then run this program. The test result is changed to Chinese (for example ), if locale is set to English, the above English information is displayed.


Back to Top

Automatically generate makefile and Package

Automatic Generation of makefile files is a wish of many Linux programmers. In fact, as long as you use Autoconf and automake tools, you can easily generate makefile files, package (generate source code package in * .tar.gz format. The configuration files related to these two tools are Configure. In And makefile. am. As long as we understand the formats and related macros of these two files, we can.


The premise is to prepare the corresponding directory and source program file, such as hello. c In the hello directory in this example.

1. First run the autoscan command to generate the configure. Scan file;

2. Execute MV Configure. Scan Configure. In and rename it;

3. Edit configure. in, in ac_init (hello. c) then add a line, am_init_automake (hello, 1.0) indicates that the package name is hello, version is 1.0, so after make compilation, execute make DIST to generate a package named hello-1.0.tar.gz source code, this is a relatively GNU open-source standard format. Add makefile to the brackets of the last ac_output () to output the makefile (configure. there are many macro definitions in the in file. For detailed usage, refer to the autobook book.) EDIT configure now. the in file ends;

4. Execute the aclocal command to generate the aclocal. M4 macro file;

5. Run the Autoconf command to generate the configure shell executable script;

6. Edit the makefile. Am file with the following content:

Automake_options = foreign
Primary des = 'pkg-config -- cflags GTK +-2.0'
Libs = 'pkg-config -- libs GTK +-2.0'
Bin_programs = Hello
Hello_sources = Hello. c

Note: The parameter of the automake command in the first action is external and does not comply with the GNU standard (that is, files such as instructions, installation, and change records are not added). The second line indicates the directory containing files; the third line indicates the directory of the Dynamic Link Library and the Library to be linked. The fourth line indicates the output executable file name. The last line indicates the source program file of the executable file, which may contain multiple file names.

7. Run the automake -- add-missing-Copy command to create the makefile. the in file is added to the lost file and copied at the same time (by default, it is a symbolic link, which may cause problems between different file systems). This operation has been completed.

Compile, test, install and Package

Run. /configure generate makefile; execute make compilation; execute. /Hello run this program. Run make install to install the program. By default, the executable file hello is copied to the/usr/local/bin directory. Execute make distcommand to generate the hello-1.0.tar.gz source code package in the current directory, in this way, you can publish your source code package to the outside world.


Back to Top

Thread used

In GTK +, apart from g_thread_init and g_thread_supported functions in glib, gdk_thread_init is also used to initialize thread applications in X Window, in addition, you must execute the gdk_thread_enter function before performing operations on the GTK + control in the thread. After the operation is complete, execute the gdk_thread_leave function to exit. This is also true when you execute the GTK + main loop, GTK + to achieve thread security. The following code uses a thread to create an image that moves clockwise on the screen (24x24 pixels ):

// Thread. c
# Include <GTK/GTK. h>
Typedef struct _ ourarg;
Struct _ ourarg {
Gtkwidget * fixed;
Gtkwidget * image;
Gint right;
Gint left;
Voidimage_go (ourarg * Arg)
Gint X, Y, toward;
X = y = Arg-> left;
Toward = 1;
For (;;)
G_usleep (1500 );
Gdk_threads_enter ();
Gtk_fixed_move (gtk_fixed (Arg-> fixed), Arg-> image, x, y );
Switch (toward)
Case 1:
X = x + 10;
If (x> Arg-> right) toward = 2;
Case 2:
Y = Y + 10;
If (Y> Arg-> right) toward = 3;
Case 3:
X = x-10;
If (x <Arg-> left) toward = 4;
Case 4:
Y = Y-10;
If (Y <Arg-> left) toward = 1;
Gdk_threads_leave ();
Intmain (INT argc, char * argv [])
Gtkwidget * window;
Gtkwidget * vbox, * viewport, * button;
Gtkwidget * image, * fixed;
Ourarg * ARG;
If (! G_thread_supported () g_thread_init (null );
Gdk_threads_init ();
Gtk_init (& argc, & argv );
Window = gtk_window_new (gtk_window_toplevel );
Gtk_window_set_title (gtk_window (window), "thread test ");
G_signal_connect (g_object (window), "delete_event ",
G_callback (gtk_main_quit), null );
Gtk_container_set_border_width (gtk_container (window), 2 );
Vbox = gtk_vbox_new (false, 0 );
Gtk_container_add (gtk_container (window), vbox );
Fixed = gtk_fixed_new ();
Gtk_widget_set_usize (fixed, 340,340 );
Viewport = gtk_viewport_new (null, null );
Gtk_box_pack_start (gtk_box (vbox), viewport, false, false, 5 );
Gtk_container_add (gtk_container (viewport), fixed );
Image = gtk_image_new_from_file ("ss.png ");
Gtk_fixed_put (gtk_fixed (fixed), image, 40, 40 );
Button = gtk_button_new_with_label ("exit ");
Gtk_box_pack_start (gtk_box (vbox), button, false, false, 5 );
G_signal_connect (g_object (button), "clicked ",
G_callback (gtk_main_quit), null );
Gtk_widget_show_all (window );
Arg = g_new (ourarg, 1 );
Arg-> fixed = fixed;
Arg-> image = image;
Arg-> left = 40;
Arg-& gt; Right = 260;
G_thread_create (image_go, ARG, false, null );
Gdk_threads_enter ();
Gtk_main ();
Gdk_threads_leave ();
Return false;

Based on thread security considerations, you must run the following code before the gtk_init function:

If (! G_thread_supported () g_thread_init (null );
Gdk_threads_init ();

The thread executes an endless loop and constantly moves the image control in the gtkfixed control to change the direction based on the image position.

(This image is not very good, just to prove that the test results of the program can run normally and can be deleted)


Back to Top


The best way to learn GTK + is to study the routines in the GTK + source code package and the source code package of open source software for other applications GTK +, there are many experts in this field on the largest Linux forum in China.

If your English is good enough, you can subscribe to the GTK + application development email list, so that you can receive several emails about GTK + development every day, I have received nearly 30 emails a day at most. Many of them will answer your questions or give you some advice.

In the selection of QT and GTK +, we often see some disputes from netizens. For the development of GUI applications on Linux platforms in China, it is imperative for the free community to put aside disputes, learn with great concentration, share experiences, form cooperation, and make open-source projects with Application Prospects and characteristics.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.