GTK+/Começando: diferenças entre revisões

[edição não verificada][edição não verificada]
Conteúdo apagado Conteúdo adicionado
Edudobay (discussão | contribs)
Sem resumo de edição
Edudobay (discussão | contribs)
Sem resumo de edição
Linha 1:
{{emtraducao2}}
= Capítulo 3. Começando =
 
Linha 75 ⟶ 76:
#include <gtk/gtk.h>
/* Esta é uma função callback. Os argumentos de dados são ignorados
/* This is a callback function. The data arguments are ignored
* inneste this exampleexemplo. MoreMais onsobre callbacks belowabaixo. */
static void hello( GtkWidget *widget,
gpointer data )
Linha 87 ⟶ 88:
gpointer data )
{
/* IfSe youvocê returnretornar FALSE inno thetratador do sinal "delete_event" signal handler,
* o GTK willemitirá emito thesinal "destroy" signal. ReturningRetornar TRUE meanssignifica
* youque don'tvocê wantnão thequer windowque toa bejanela destroyedseja destruída.
* ThisIsso isé usefulútil forpara poppingexibir updiálogos 'aredo youtipo sure'tem youcerteza want to quit?'de
* typeque dialogsdeseja sair?'. */
g_print ("deleteevento event'delete' occurredocorreu\n");
/* ChangeMude TRUE topara FALSE ande thea mainjanela windowprincipal willserá bedestruída destroyedcom withum
* a "delete_event". */
return TRUE;
}
/* AnotherOutro callback */
static void destroy( GtkWidget *widget,
gpointer data )
Linha 111 ⟶ 112:
char *argv[] )
{
/* GtkWidget isé theo storagetipo typede fordado para os widgets */
GtkWidget *window;
GtkWidget *button;
/* ThisEsta isfunção calledé inchamada allem GTKtodas applicationsas aplicações GTK. ArgumentsArgumentos areda parsedlinha
* fromde thecomando commandsão lineinterpretados ande areretornados returnedà to the applicationaplicação. */
gtk_init (&argc, &argv);
/* createcriar auma newnova windowjanela */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
/* WhenQuando thea windowjanela isrecebe giveno thesinal "delete_event" signal (thisdado ispelo givengerenciador
* byde the window managerjanelas, usuallygeralmente bypela theopção "closefechar" option, orou onna thebarra de título),
* titlebar),nós wepedimos askque itela tochame calla thefunção delete_event () functioncomo definido
* as defined aboveacima. TheOs datadado passedpassado topara thea função callback é NULL e é ignorado. */
* function is NULL and is ignored in the callback function. */
g_signal_connect (G_OBJECT (window), "delete_event",
G_CALLBACK (delete_event), NULL);
/* HereAqui weconectamos connecto theevento "destroy" eventa toum atratador signalde handlersinal. Esse
* Thisevento eventocorre occursquando when we callchamamos gtk_widget_destroy() onna thejanela, window,ou
* orse if we returnretornamos FALSE inno thecallback "delete_event" callback. */
g_signal_connect (G_OBJECT (window), "destroy",
G_CALLBACK (destroy), NULL);
/* SetsAjusta thea borderlargura widthda ofborda theda windowjanela. */
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* CreatesCria aum newnovo buttonbotão withcom theo labeltexto "Hello World". */
button = gtk_button_new_with_label ("Hello World");
/* WhenQuando theo buttonbotão receivesrecebe theo sinal "clicked" signal, itchamará willa callfunção thehello()
* functionpassando NULL como argumento. hello() passingé itdefinida NULL as its argumentacima. The hello()*/
* function is defined above. */
g_signal_connect (G_OBJECT (button), "clicked",
G_CALLBACK (hello), NULL);
/* ThisIsso willfará causecom theque windowa tojanela beserá destroyeddestruída bypela callingchamada
* gtk_widget_destroy(window) whenquando "clicked".o botão Again,for theclicado destroy("clicked").
* signalNovamente, couldo comesinal fromdestroy here,poderia orvir thedaqui windowou manager.do */gerenciador
* de janelas. */
g_signal_connect_swapped (G_OBJECT (button), "clicked",
G_CALLBACK (gtk_widget_destroy),
G_OBJECT (window));
/* ThisIsto packsempacota theo buttonbotão intona the windowjanela (aum recipiente gtk container). */
gtk_container_add (GTK_CONTAINER (window), button);
/* TheO passo final stepé isexibir too displaywidget this newly created widgetrecém-criado. */
gtk_widget_show (button);
/* ande thea windowjanela */
gtk_widget_show (window);
/* AllToda aplicação GTK applicationsdeve mustter haveuma achamada gtk_main(). Control endsO herecontrole
* andtermina waitsaqui fore anespera eventpor toum occurevento (likecomo aum keyapertamento pressde ortecla
* mouseou eventevento do mouse). */
gtk_main ();
return 0;
}
 
== Compilando o Hello World ==
 
Para compilar use:
== Teoria dos sinais e dos callbacks ==
 
gcc -Wall -g helloworld.c -o helloworld `pkg-config --cflags gtk+-2.0` \
`pkg-config --libs gtk+-2.0`
 
Usamos o programa <tt>pkg-config</tt>, que pode ser obtido de www.freedesktop.org. Esse programa lê o arquivo <tt>.pc</tt> que vem com o GTK para determinar as opções do compilador necessárias para compilar programas que usam GTK. <tt>pkg-config --cflags gtk+-2.0</tt> mostrará uma lista de diretórios de inclusão nos quais o compilador deve olhar, e <tt>pkg-config --libs gtk+-2.0</tt> mostrará a lista de bibliotecas às quais o compilador deve ligar o executável e os diretórios nos quais encontrá-las. No exemplo acima os dois comandos poderiam ter sido combinados num só, como <tt>pkg-config --cflags --libs gtk+-2.0</tt>.
 
Note que você deve digitar um "acento grave" e não uma aspa simples.
 
As bibliotecas que costumam ser usadas são:
 
* A biblioteca GTK (-lgtk), a biblioteca de widgets, baseada no GDK.
* A biblioteca GDK (-lgdk), o intermediário da Xlib.
* A biblioteca gdk-pixbuf (-lgdk_pixbuf), a biblioteca de manipulação de imagens.
* A biblioteca Pango (-lpango) para texto internationalizado.
* A biblioteca gobject (-lgobject), que contém o sistema de tipos no qual é baseado o GTK.
* A biblioteca gmodule (-lgmodule), usada para carregar extensões em tempo de execução.
* A biblioteca GLib (-lglib), que contém funções miscelâneas; apenas g_print() é usada neste exemplo particular. O GTK é construído sobre a GLib, portanto você sempre precisará desta biblioteca. Veja a seção sobre a GLib para mais detalhes.
* A biblioteca Xlib (-lX11) que é usada pelo GDK.
* A biblioteca Xext (-lXext). Ela contém código para pixmaps compartilhados na memória e outras extensões X.
* A biblioteca de matemática (-lm). É usada pelo GTK para vários propósitos.
 
== Teoria dos sinais e dos callbacks ==
 
<div style="background-color: #fffac1; margin: 20px; padding: 10px;">
Na versão 2.0, o sistema de sinais foi movido do GTK para a GLib, portanto as funções e tipos explicadas nesta seção têm o prefixo "g_" e não "gtk_". Não falaremos em detalhes sobre as extensões do sistema de sinais da GLib 2.0 em relação ao do GTK 1.2.
</div>
 
Antes de olharmos detalhadamente para o programa helloworld, discutiremos sinais e callbacks. O GTK é uma biblioteca movida a eventos, o que significa que ele "dormirá" na função gtk_main() até que um evento ocorra e o controle seja passado para a função apropriada.
 
Essa passagem de controle é feita usando a idéia de "sinais". (Note que esses sinais não são os mesmos que os sinais de sistema Unix, e não são através deles implementados, apesar de a terminologia ser quase idêntica.) Quando um evento ocorre, como o pressionamento de um botão do mouse, o sinal apropriado será "emitido" pelo widget que foi pressionado. É assim que o GTK faz a maior parte de seu trabalho útil. Há sinais que todos os widgets herdam, como "destroy" (destruir), e há sinais específicos de um certo widget ou conjunto de widgets, como "toggled" (alternado) num botão de alternar.
 
Para fazer um botão realizar uma ação, configuramos um tratador de sinal para capturar esses sinais e chamar a função apropriada. Isso é feito com uma função como:
 
gulong g_signal_connect( gpointer *object,
const gchar *name,
GCallback func,
gpointer func_data );
 
where the first argument is the widget which will be emitting the signal, and the second the name of the signal you wish to catch. The third is the function you wish to be called when it is caught, and the fourth, the data you wish to have passed to this function.
 
The function specified in the third argument is called a "callback function", and should generally be of the form
 
void callback_func( GtkWidget *widget,
... /* other signal arguments */
gpointer callback_data );
 
where the first argument will be a pointer to the widget that emitted the signal, and the last a pointer to the data given as the last argument to the g_signal_connect() function as shown above.
 
Note that the above form for a signal callback function declaration is only a general guide, as some widget specific signals generate different calling parameters.
 
Another call used in the helloworld example, is:
 
gulong g_signal_connect_swapped( gpointer *object,
const gchar *name,
GCallback func,
gpointer *callback_data );
 
g_signal_connect_swapped() is the same as g_signal_connect() except that the instance on which the signal is emitted and data will be swapped when calling the handler. So when using this function to connect signals, the callback should be of the form
 
void callback_func( gpointer callback_data,
... /* other signal arguments */
GtkWidget *widget);
 
where the object is usually a widget. We usually don't setup callbacks for g_signal_connect_swapped() however. They are usually used to call a GTK function that accepts a single widget or object as an argument, when a signal is emitted on some other object. In the helloworld example, we connect to the "clicked" signal on the button, but call gtk_widget_destroy() on the window.
 
If your callbacks need additional data, use g_signal_connect() instead of g_signal_connect_swapped().
 
== Eventos ==
 
 
 
== Analisando o Hello World ==