File: gtkfaq-5.html

package info (click to toggle)
gtk%2B1.2 1.2.10-18
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 14,468 kB
  • ctags: 12,966
  • sloc: ansic: 137,190; sh: 13,303; makefile: 1,170; perl: 328; awk: 274; lisp: 7
file content (1036 lines) | stat: -rw-r--r-- 33,324 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
 <META NAME="GENERATOR" CONTENT="SGML-Tools 1.0.9">
 <TITLE>GTK+ FAQ: Development with GTK+: general questions</TITLE>
 <LINK HREF="gtkfaq-6.html" REL=next>
 <LINK HREF="gtkfaq-4.html" REL=previous>
 <LINK HREF="gtkfaq.html#toc5" REL=contents>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<A HREF="gtkfaq-6.html">Next</A>
<A HREF="gtkfaq-4.html">Previous</A>
<A HREF="gtkfaq.html#toc5">Contents</A>
<HR NOSHADE>
<H2><A NAME="s5">5. Development with GTK+: general questions</A></H2>

<H2><A NAME="ss5.1">5.1 What widgets are in GTK?</A>
</H2>

<P>The GTK+ Tutorial lists the following widgets:
<P>
<PRE>
  GtkObject
   +GtkData
   | +GtkAdjustment
   | `GtkTooltips
   `GtkWidget
     +GtkContainer
     | +GtkBin
     | | +GtkAlignment
     | | +GtkEventBox
     | | +GtkFrame
     | | | `GtkAspectFrame
     | | +GtkHandleBox
     | | +GtkItem
     | | | +GtkListItem
     | | | +GtkMenuItem
     | | | | `GtkCheckMenuItem
     | | | |   `GtkRadioMenuItem
     | | | `GtkTreeItem
     | | +GtkViewport
     | | `GtkWindow
     | |   +GtkColorSelectionDialog
     | |   +GtkDialog
     | |   | `GtkInputDialog
     | |   `GtkFileSelection
     | +GtkBox
     | | +GtkButtonBox
     | | | +GtkHButtonBox
     | | | `GtkVButtonBox
     | | +GtkHBox
     | | | +GtkCombo
     | | | `GtkStatusbar
     | | `GtkVBox
     | |   +GtkColorSelection
     | |   `GtkGammaCurve
     | +GtkButton
     | | +GtkOptionMenu
     | | `GtkToggleButton
     | |   `GtkCheckButton
     | |     `GtkRadioButton
     | +GtkCList
     |   `GtkCTree
     | +GtkFixed
     | +GtkList
     | +GtkMenuShell
     | | +GtkMenuBar
     | | `GtkMenu
     | +GtkNotebook
     | +GtkPaned
     | | +GtkHPaned
     | | `GtkVPaned
     | +GtkScrolledWindow
     | +GtkTable
     | +GtkToolbar
     | `GtkTree
     +GtkDrawingArea
     | `GtkCurve
     +GtkEditable
     | +GtkEntry
     | | `GtkSpinButton
     | `GtkText
     +GtkMisc
     | +GtkArrow
     | +GtkImage
     | +GtkLabel
     | | `GtkTipsQuery
     | `GtkPixmap
     +GtkPreview
     +GtkProgressBar
     +GtkRange
     | +GtkScale
     | | +GtkHScale
     | | `GtkVScale
     | `GtkScrollbar
     |   +GtkHScrollbar
     |   `GtkVScrollbar
     +GtkRuler
     | +GtkHRuler
     | `GtkVRuler
     `GtkSeparator
       +GtkHSeparator
       `GtkVSeparator
</PRE>
<P>
<H2><A NAME="ss5.2">5.2 Is GTK+ thread safe? How do I write multi-threaded GTK+ applications?</A>
</H2>

<P>The GLib library can be used in a thread-safe mode by calling
g_thread_init() before making any other GLib calls. In this mode GLib
automatically locks all internal data structures as needed.  This
does not mean that two threads can simultaneously access, for
example, a single hash table, but they can access two different hash
tables simultaneously. If two different threads need to access the
same hash table, the application is responsible for locking
itself.
<P>When GLib is intialized to be thread-safe, GTK+ is
<EM>thread aware</EM>. There is a single global lock
that you must acquire with gdk_threads_enter() before
making any GDK calls, and release with gdk_threads_leave()
afterwards.
<P>A minimal main program for a threaded GTK+ application
looks like:
<P>
<PRE>
int
main (int argc, char *argv[])
{
  GtkWidget *window;

  g_thread_init(NULL);
  gtk_init(&amp;argc, &amp;argv);

  window = create_window();
  gtk_widget_show(window);

  gdk_threads_enter();
  gtk_main();
  gdk_threads_leave();

  return(0);
}
</PRE>
<P>Callbacks require a bit of attention. Callbacks from GTK+
(signals) are made within the GTK+ lock. However callbacks
from GLib (timeouts, IO callbacks, and idle functions)
are made outside of the GTK+ lock. So, within a signal
handler you do not need to call gdk_threads_enter(), but
within the other types of callbacks, you do.
<P>Erik Mouw contributed the following code example to illustrate how to
use threads within GTK+ programs.
<P>
<BLOCKQUOTE><CODE>
<PRE>
/*-------------------------------------------------------------------------
 * Filename:      gtk-thread.c
 * Version:       0.99.1
 * Copyright:     Copyright (C) 1999, Erik Mouw
 * Author:        Erik Mouw &lt;J.A.K.Mouw@its.tudelft.nl>
 * Description:   GTK threads example. 
 * Created at:    Sun Oct 17 21:27:09 1999
 * Modified by:   Erik Mouw &lt;J.A.K.Mouw@its.tudelft.nl>
 * Modified at:   Sun Oct 24 17:21:41 1999
 *-----------------------------------------------------------------------*/
/*
 * Compile with:
 *
 * cc -o gtk-thread gtk-thread.c `gtk-config --cflags --libs gthread`
 *
 * Thanks to Sebastian Wilhelmi and Owen Taylor for pointing out some
 * bugs.
 *
 */

#include &lt;stdio.h>
#include &lt;stdlib.h>
#include &lt;unistd.h>
#include &lt;time.h>
#include &lt;gtk/gtk.h>
#include &lt;glib.h>
#include &lt;pthread.h>

#define YES_IT_IS    (1)
#define NO_IT_IS_NOT (0)

typedef struct 
{
  GtkWidget *label;
  int what;
} yes_or_no_args;

G_LOCK_DEFINE_STATIC (yes_or_no);
static volatile int yes_or_no = YES_IT_IS;

void destroy(GtkWidget *widget, gpointer data)
{
  gtk_main_quit();
}

void *argument_thread(void *args)
{
  yes_or_no_args *data = (yes_or_no_args *)args;
  gboolean say_something;

  for(;;)
    {
      /* sleep a while */
      sleep(rand() / (RAND_MAX / 3) + 1);

      /* lock the yes_or_no_variable */
      G_LOCK(yes_or_no);

      /* do we have to say something? */
      say_something = (yes_or_no != data->what);

      if(say_something)
        {
          /* set the variable */
          yes_or_no = data->what;
        }

      /* Unlock the yes_or_no variable */
      G_UNLOCK(yes_or_no);

      if(say_something)
        {
          /* get GTK thread lock */
          gdk_threads_enter();

          /* set label text */
          if(data->what == YES_IT_IS)
            gtk_label_set_text(GTK_LABEL(data->label), "O yes, it is!");
          else
            gtk_label_set_text(GTK_LABEL(data->label), "O no, it isn't!");

          /* release GTK thread lock */
          gdk_threads_leave();
        }
    }

  return(NULL);
}

int main(int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *label;
  yes_or_no_args yes_args, no_args;
  pthread_t no_tid, yes_tid;

  /* init threads */
  g_thread_init(NULL);

  /* init gtk */
  gtk_init(&amp;argc, &amp;argv);

  /* init random number generator */
  srand((unsigned int)time(NULL));

  /* create a window */
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  gtk_signal_connect(GTK_OBJECT (window), "destroy",
                     GTK_SIGNAL_FUNC(destroy), NULL);

  gtk_container_set_border_width(GTK_CONTAINER (window), 10);

  /* create a label */
  label = gtk_label_new("And now for something completely different ...");
  gtk_container_add(GTK_CONTAINER(window), label);
  
  /* show everything */
  gtk_widget_show(label);
  gtk_widget_show (window);

  /* create the threads */
  yes_args.label = label;
  yes_args.what = YES_IT_IS;
  pthread_create(&amp;yes_tid, NULL, argument_thread, &amp;yes_args);

  no_args.label = label;
  no_args.what = NO_IT_IS_NOT;
  pthread_create(&amp;no_tid, NULL, argument_thread, &amp;no_args);

  /* enter the GTK main loop */
  gdk_threads_enter();
  gtk_main();
  gdk_threads_leave();

  return(0);
}
</PRE>
</CODE></BLOCKQUOTE>
<P>
<P>
<H2><A NAME="ss5.3">5.3 Why does this strange 'x io error' occur when I <CODE>fork()</CODE> in my GTK+ app?</A>
</H2>

<P>This is not really a GTK+ problem, and the problem is not related to
<CODE>fork()</CODE> either. If the 'x io error' occurs then you probably use
the <CODE>exit()</CODE> function in order to exit from the child process.
<P>When GDK opens an X display, it creates a socket file descriptor. When
you use the <CODE>exit()</CODE> function, you implicitly close all the open
file descriptors, and the underlying X library really doesn't like
this.
<P>The right function to use here is <CODE>_exit()</CODE>. 
<P>Erik Mouw contributed the following code example to illustrate
handling fork() and exit().
<P>
<BLOCKQUOTE><CODE>
<PRE>
/*-------------------------------------------------------------------------
 * Filename:      gtk-fork.c
 * Version:       0.99.1
 * Copyright:     Copyright (C) 1999, Erik Mouw
 * Author:        Erik Mouw &lt;J.A.K.Mouw@its.tudelft.nl>
 * Description:   GTK+ fork example
 * Created at:    Thu Sep 23 21:37:55 1999
 * Modified by:   Erik Mouw &lt;J.A.K.Mouw@its.tudelft.nl>
 * Modified at:   Thu Sep 23 22:39:39 1999
 *-----------------------------------------------------------------------*/
/*
 * Compile with:
 *
 * cc -o gtk-fork gtk-fork.c `gtk-config --cflags --libs`
 *
 */

#include &lt;stdio.h>
#include &lt;stdlib.h>
#include &lt;signal.h>
#include &lt;sys/types.h>
#include &lt;sys/wait.h>
#include &lt;unistd.h>
#include &lt;gtk/gtk.h>

void sigchld_handler(int num)
{
  sigset_t set, oldset;
  pid_t pid;
  int status, exitstatus;

  /* block other incoming SIGCHLD signals */
  sigemptyset(&amp;set);
  sigaddset(&amp;set, SIGCHLD);
  sigprocmask(SIG_BLOCK, &amp;set, &amp;oldset);

  /* wait for child */
  while((pid = waitpid((pid_t)-1, &amp;status, WNOHANG)) > 0)
    {
      if(WIFEXITED(status))
        {
          exitstatus = WEXITSTATUS(status);

          fprintf(stderr, 
                  "Parent: child exited, pid = %d, exit status = %d\n", 
                  (int)pid, exitstatus);
        }
      else if(WIFSIGNALED(status))
        {
          exitstatus = WTERMSIG(status);

          fprintf(stderr,
                  "Parent: child terminated by signal %d, pid = %d\n",
                  exitstatus, (int)pid);
        }
      else if(WIFSTOPPED(status))
        {
          exitstatus = WSTOPSIG(status);

          fprintf(stderr,
                  "Parent: child stopped by signal %d, pid = %d\n",
                  exitstatus, (int)pid);
        }
      else
        {
          fprintf(stderr,
                  "Parent: child exited magically, pid = %d\n",
                  (int)pid);
        }
    }

  /* re-install the signal handler (some systems need this) */
  signal(SIGCHLD, sigchld_handler);
  
  /* and unblock it */
  sigemptyset(&amp;set);
  sigaddset(&amp;set, SIGCHLD);
  sigprocmask(SIG_UNBLOCK, &amp;set, &amp;oldset);
}

gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data)
{
  return(FALSE);
}

void destroy(GtkWidget *widget, gpointer data)
{
  gtk_main_quit();
}

void fork_me(GtkWidget *widget, gpointer data)
{
  pid_t pid;

  pid = fork();

  if(pid == -1)
    {
      /* ouch, fork() failed */
      perror("fork");
      exit(-1);
    }
  else if(pid == 0)
    {
      /* child */
      fprintf(stderr, "Child: pid = %d\n", (int)getpid());

      execlp("ls", "ls", "-CF", "/", NULL);
      
      /* if exec() returns, there is something wrong */
      perror("execlp");

      /* exit child. note the use of _exit() instead of exit() */
      _exit(-1);
    }
  else
    {
      /* parent */
      fprintf(stderr, "Parent: forked a child with pid = %d\n", (int)pid);
    }
}

int main(int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *button;

  gtk_init(&amp;argc, &amp;argv);

  /* the basic stuff: make a window and set callbacks for destroy and
   * delete events 
   */
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  gtk_signal_connect(GTK_OBJECT (window), "delete_event",
                     GTK_SIGNAL_FUNC(delete_event), NULL);
          
  gtk_signal_connect(GTK_OBJECT (window), "destroy",
                     GTK_SIGNAL_FUNC(destroy), NULL);

#if (GTK_MAJOR_VERSION == 1) &amp;&amp; (GTK_MINOR_VERSION == 0)
  gtk_container_border_width(GTK_CONTAINER (window), 10);
#else  
  gtk_container_set_border_width(GTK_CONTAINER (window), 10);
#endif

  /* add a button to do something usefull */
  button = gtk_button_new_with_label("Fork me!");
          
  gtk_signal_connect(GTK_OBJECT (button), "clicked",
                     GTK_SIGNAL_FUNC(fork_me), NULL);

  gtk_container_add(GTK_CONTAINER(window), button);
          
  /* show everything */
  gtk_widget_show (button);
  gtk_widget_show (window);


  /* install a signal handler for SIGCHLD signals */
  signal(SIGCHLD, sigchld_handler);

  
  /* main loop */
  gtk_main ();

  exit(0);         
}
</PRE>
</CODE></BLOCKQUOTE>
<P>
<H2><A NAME="ss5.4">5.4 Why don't the contents of a button move when the button is pressed? Here's a patch to make it work that way...</A>
</H2>

<P>From: Peter Mattis
<P>
<BLOCKQUOTE>
The reason buttons don't move their child down and to the right when
they are depressed is because I don't think that's what is happening
visually. My view of buttons is that you are looking at them straight
on. That is, the user interface lies in a plane and you're above it
looking straight at it. When a button gets pressed it moves directly
away from you. To be absolutely correct I guess the child should
actually shrink a tiny amount. But I don't see why the child should
shift down and to the left. Remember, the child is supposed to be
attached to the buttons surface. Its not good for it to appear like
the child is slipping on the surface of the button.
<P>On a more practical note, I did implement this at one point and
determined it didn't look good and removed it.
</BLOCKQUOTE>
     
<P>
<H2><A NAME="ss5.5">5.5 How to I identifiy a widgets top level window or other ancestor?</A>
</H2>

<P>There are a couple of ways to find the top level parent of a
widget. The easier way is to call the <CODE>gtk_widget_top_level()</CODE>
function that returns a pointer to a GtkWidget that is the top level
window.
<P>A more complicated way to do this (but less limited, as it allows
the user to get the closest ancestor of a known type) is to use
<CODE>gtk_widget_get_ancestor()</CODE> as in:
<P>
<BLOCKQUOTE><CODE>
<PRE>
      GtkWidget       *widget;
      
      widget = gtk_widget_get_ancestor(w, GTK_TYPE_WINDOW);
</PRE>
</CODE></BLOCKQUOTE>
<P>Since virtually all the GTK_TYPEs can be used as the second parameter
of this function, you can get any parent widget of a particular
widget. Suppose you have an hbox which contains a vbox, which in turn
contains some other atomic widget (entry, label, etc. To find the
master hbox using the <CODE>entry</CODE> widget simply use:
<P>
<BLOCKQUOTE><CODE>
<PRE>
      GtkWidget       *hbox;
      hbox = gtk_widget_get_ancestor(w, GTK_TYPE_HBOX);
</PRE>
</CODE></BLOCKQUOTE>
<P>
<H2><A NAME="ss5.6">5.6 How do I get the Window ID of a GtkWindow?</A>
</H2>

<P>The actual Gdk/X window will be created when the widget gets
realized. You can get the Window ID with:
<P>
<PRE>
#include &lt;gdk/gdkx.h>

Window xwin = GDK_WINDOW_XWINDOW (GTK_WIDGET (my_window)->window);
</PRE>
<P>
<H2><A NAME="ss5.7">5.7 How do I catch a double click event (in a list widget, for example)?</A>
</H2>

<P>Tim Janik wrote to gtk-list (slightly modified):
<P>Define a signal handler:
<P>
<BLOCKQUOTE><CODE>
<PRE>
gint
signal_handler_event(GtkWidget *widget, GdkEventButton *event, gpointer func_data)
{
  if (GTK_IS_LIST_ITEM(widget) &amp;&amp;
       (event->type==GDK_2BUTTON_PRESS ||
        event->type==GDK_3BUTTON_PRESS) ) {
    printf("I feel %s clicked on button %d\n",
           event->type==GDK_2BUTTON_PRESS ? "double" : "triple",
           event->button);
  }

  return FALSE;
}
</PRE>
</CODE></BLOCKQUOTE>
<P>And connect the handler to your object:
<P>
<BLOCKQUOTE><CODE>
<PRE>
{
  /* list, list item init stuff */     

  gtk_signal_connect(GTK_OBJECT(list_item),
                     "button_press_event",
                     GTK_SIGNAL_FUNC(signal_handler_event),
                     NULL);

  /* and/or */

  gtk_signal_connect(GTK_OBJECT(list_item),
                     "button_release_event",
                     GTK_SIGNAL_FUNC(signal_handler_event),
                     NULL);

  /* something else */
}
</PRE>
</CODE></BLOCKQUOTE>
<P>and, Owen Taylor wrote:
<P>Note that a single button press will be received beforehand, and
if you are doing this for a button, you will therefore also get a
"clicked" signal for the button. (This is going to be true for
any toolkit, since computers aren't good at reading one's
mind.)
<P>
<H2><A NAME="ss5.8">5.8 By the way, what are the differences between signals and events?</A>
</H2>

<P>First of all, Havoc Pennington gives a rather complete description of
the differences between events and signals in his free book (two
chapters can be found at 
<A HREF="http://www106.pair.com/rhp/sample_chapters.html">http://www106.pair.com/rhp/sample_chapters.html</A>).
<P>Moreover, Havoc posted this to the <CODE>gtk-list</CODE>
<BLOCKQUOTE>
Events are a stream of messages received from the X server. They
drive the Gtk main loop; which more or less amounts to "wait for
events, process them" (not exactly, it is really more general than
that and can wait on many different input streams at once). Events
are a Gdk/Xlib concept.
<P>Signals are a feature of GtkObject and its subclasses. They have
nothing to do with any input stream; really a signal is just a way
to keep a list of callbacks around and invoke them ("emit" the
signal). There are lots of details and extra features of
course. Signals are emitted by object instances, and are entirely
unrelated to the Gtk main loop.  Conventionally, signals are emitted
"when something changes" about the object emitting the signal.
<P>Signals and events only come together because GtkWidget happens to
emit signals when it gets events. This is purely a convenience, so
you can connect callbacks to be invoked when a particular widget
receives a particular event. There is nothing about this that makes
signals and events inherently related concepts, any more than
emitting a signal when you click a button makes button clicking and
signals related concepts.
</BLOCKQUOTE>
<P>
<H2><A NAME="ss5.9">5.9 Data I pass to the <CODE>delete_event</CODE> (or other event) handler gets corrupted.</A>
</H2>

<P>All event handlers take an additional argument which contains
information about the event that triggered the handler. So, a
<CODE>delete_event</CODE> handler must be declared as:
<P>
<BLOCKQUOTE><CODE>
<PRE>
gint delete_event_handler (GtkWidget   *widget,
                           GdkEventAny *event,
                           gpointer     data);
</PRE>
</CODE></BLOCKQUOTE>
<P>
<H2><A NAME="ss5.10">5.10 I have my signal connected to the the (whatever) event, but it seems I don't catch it. What's wrong?</A>
</H2>

<P>There is some special initialisation to do in order to catch some
particular events. In fact, you must set the correct event mask bit of
your widget before getting some particular events.
<P>For example, 
<P>
<BLOCKQUOTE><CODE>
<PRE>
  gtk_widget_add_events(window, GDK_KEY_RELEASE_MASK);
</PRE>
</CODE></BLOCKQUOTE>
<P>lets you catch the key release events. If you want to catch every events,
simply us the GDK_ALL_EVENTS_MASK event mask.
<P>All the event masks are defined in the <CODE>gdktypes.h</CODE> file.
<P>
<H2><A NAME="ss5.11">5.11 I need to add a new signal to a GTK+ widget. Any idea?</A>
</H2>

<P>If the signal you want to add may be beneficial for other GTK+ users,
you may want to submit a patch that presents your changes. Check the
tutorial for more information about adding signals to a widget class.
<P>If you don't think it is the case or if your patch is not applied
you'll have to use the <CODE>gtk_object_class_user_signal_new</CODE>
function. <CODE>gtk_object_class_user_signal_new</CODE> allows you to add a
new signal to a predefined GTK+ widget without any modification of the
GTK+ source code. The new signal can be emited with
<CODE>gtk_signal_emit</CODE> and can be handled in the same way as other
signals.
<P>Tim Janik posted this code snippet:
<P>
<BLOCKQUOTE><CODE>
<PRE>
static guint signal_user_action = 0;

signal_user_action =
  gtk_object_class_user_signal_new (gtk_type_class (GTK_TYPE_WIDGET),
                    "user_action",
                    GTK_RUN_LAST | GTK_RUN_ACTION,
                    gtk_marshal_NONE__POINTER,
                    GTK_TYPE_NONE, 1,
                    GTK_TYPE_POINTER);

void
gtk_widget_user_action (GtkWidget *widget,
                        gpointer   act_data)
{
  g_return_if_fail (GTK_IS_WIDGET (widget));

  gtk_signal_emit (GTK_OBJECT (widget), signal_user_action, act_data);
}
</PRE>
</CODE></BLOCKQUOTE>
<P>If you want your new signal to have more than the classical gpointer
parameter, you'll have to play with GTK+ marshallers.
<P>
<H2><A NAME="ss5.12">5.12 Is it possible to get some text displayed which is truncated to fit inside its allocation? </A>
</H2>

<P>GTK's behavior (no clipping) is a consequence of its attempts to
conserve X resources. Label widgets (among others) don't get their own
X window - they just draw their contents on their parent's window.
While it might be possible to have clipping occur by setting the clip
mask before drawing the text, this would probably cause a substantial
performance penalty.
<P>Its possible that, in the long term, the best solution to such
problems might be just to change gtk to give labels X windows.
A short term workaround is to put the label widget inside another
widget that does get its own window - one possible candidate would
be the viewport widget.
<P>
<BLOCKQUOTE><CODE>
<PRE>
viewport = gtk_viewport (NULL, NULL);
gtk_widget_set_usize (viewport, 50, 25);
gtk_viewport_set_shadow_type (GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
gtk_widget_show(viewport);

label = gtk_label ("a really long label that won't fit");
gtk_container_add (GTK_CONTAINER(viewport), label);
gtk_widget_show (label);
</PRE>
</CODE></BLOCKQUOTE>
<P>If you were doing this for a bunch of widgets, you might want to
copy gtkviewport.c and strip out the adjustment and shadow
functionality (perhaps you could call it GtkClipper).
<P>
<P>
<H2><A NAME="ss5.13">5.13 How do I make my window modal? / How do I make a single window active?</A>
</H2>

<P>After you create your window, do <CODE>gtk_grab_add(my_window)</CODE>. And after 
closing the window do <CODE>gtk_grab_remove(my_window)</CODE>.
<P>
<H2><A NAME="ss5.14">5.14 Why doesn't my widget (e.g. progressbar) update?</A>
</H2>

<P>
<P>You are probably doing all the changes within a function without
returning control to <CODE>gtk_main()</CODE>. This may be the case if you do
some lengthy calculation in your code. Most drawing updates are only
placed on a queue, which is processed within <CODE>gtk_main()</CODE>. You can
force the drawing queue to be processed using something like:
<P>
<BLOCKQUOTE><CODE>
<PRE>
while (gtk_main_iteration(FALSE));
</PRE>
</CODE></BLOCKQUOTE>
<P>inside you're function that changes the widget.
<P>What the above snippet does is run all pending events and high priority 
idle functions, then return immediately (the drawing is done in a 
high priority idle function).
<P>
<H2><A NAME="ss5.15">5.15 How do I attach data to some GTK+ object/widget?</A>
</H2>

<P>First of all, the attached data is stored in the object_data field of
a GtkObject. The type of this field is GData, which is defined in
glib.h.  So you should read the gdataset.c file in your glib source
directory very carefully.
<P>There are two (easy) ways to attach some data to a gtk object.  Using
<CODE>gtk_object_set_data()</CODE> and <CODE>gtk_object_get_data()</CODE> seems to be
the most common way to do this, as it provides a powerful interface to
connect objects and data.
<P>
<BLOCKQUOTE><CODE>
<PRE>
void gtk_object_set_data(GtkObject *object, const gchar *key, gpointer data);

gpointer gtk_object_get_data(GtkObject *object, const gchar *key);
</PRE>
</CODE></BLOCKQUOTE>
<P>Since a short example is better than any lengthy speech:
<P>
<BLOCKQUOTE><CODE>
<PRE>
struct my_struct        p1,p2,*result;
GtkWidget               *w;

gtk_object_set_data(GTK_OBJECT(w),"p1 data",(gpointer)&amp;p1);
gtk_object_set_data(GTK_OBJECT(w),"p2 data",(gpointer)&amp;p2);

result = gtk_object_get_data(GTK_OBJECT(w),"p1 data");
</PRE>
</CODE></BLOCKQUOTE>
<P>The <CODE>gtk_object_set_user_data()</CODE> and <CODE>gtk_object_get_user_data()</CODE>
functions does exactly the same thing
as the functions above, but does not let you specify the "key" parameter.
Instead, it uses a standard "user_data" key. Note that the use of these
functions is deprecated in 1.2. They only provide a compatibility mode 
with some old gtk packages.
<P>
<H2><A NAME="ss5.16">5.16 How do I remove the data I have attached to an object?</A>
</H2>

<P>When attaching the data to the object, you can use the
<CODE>gtk_object_set_data_full()</CODE> function. The three first arguments of
the function are the same as in <CODE>gtk_object_set_data()</CODE>. The fourth
one is a pointer to a callback function which is called when the data
is destroyed. The data is destroyed when you:
<P>
<UL>
<LI> destroy the object</LI>
<LI> replace the data with a new one (with the same key)</LI>
<LI> replace the data with NULL (with the same key)</LI>
</UL>
<P>
<H2><A NAME="ss5.17">5.17 How do I reparent a widget?</A>
</H2>

<P>The normal way to reparent (ie change the owner) of a widget should be
to use the function:
<P>
<BLOCKQUOTE><CODE>
<PRE>
void gtk_widget_reparent (GtkWidget *widget, 
                          GtkWidget *new_parent)
</PRE>
</CODE></BLOCKQUOTE>
<P>But this is only a "should be" since this function does not correctly
do its job on some specific widgets. The main goal of
gtk_widget_reparent() is to avoid unrealizing widget if both widget
and new_parent are realized (in this case, widget->window is
successfully reparented). The problem here is that some widgets in the
GTK+ hierarchy have multiple attached X subwindows and this is notably
the case for the GtkSpinButton widget. For those,
gtk_widget_reparent() will fail by leaving an unrealized child window
where it should not.
<P>To avoid this problem, simply use the following code snippet: 
<P>
<BLOCKQUOTE><CODE>
<PRE>
     gtk_widget_ref(widget);
     gtk_container_remove(GTK_CONTAINER(old_parent), widget);
     gtk_container_add(GTK_CONTAINER(new_parent), widget);
     gtk_widget_unref(widget);
</PRE>
</CODE></BLOCKQUOTE>
<P>
<H2><A NAME="ss5.18">5.18 How could I get any widgets position?</A>
</H2>

<P>As Tim Janik pointed out, there are different cases, and each case
requires a different solution.
<P>
<UL>
<LI> If you want the position of a widget relative to its parent,
you should use <CODE>widget->allocation.x</CODE> and
<CODE>widget->allocation.y</CODE>.</LI>
<LI> If you want the position of a window relative to the X root
window, you should use <CODE>gdk_window_get_geometry()</CODE>
<CODE>gdk_window_get_position()</CODE> or
<CODE>gdk_window_get_origin()</CODE>.</LI>
<LI> If you want to get the position of the window (including the WM
decorations), you should use
<CODE>gdk_window_get_root_origin()</CODE>.</LI>
<LI> Last but not least, if you want to get a Window Manager frame
position, you should use
<CODE>gdk_window_get_deskrelative_origin()</CODE>.</LI>
</UL>
<P>Your choice of Window Manager will have an effect of the results of
the above functions. You should keep this in mind when writing your
application. This is dependant upon how the Window Managers manage the
decorations that they add around windows.
<P>
<H2><A NAME="ss5.19">5.19 How do I set the size of a widget/window? How do I prevent the user resizing my window?</A>
</H2>

<P>The <CODE>gtk_widget_set_uposition()</CODE> function is used to set the
position of any widget.
<P>The <CODE>gtk_widget_set_usize()</CODE> function is used to set the size of a
widget. In order to use all the features that are provided by this
function when it acts on a window, you may want to use the
<CODE>gtk_window_set_policy</CODE> function. The definition of these functions
are:
<P>
<BLOCKQUOTE><CODE>
<PRE>
void gtk_widget_set_usize (GtkWidget *widget,
                           gint width,
                           gint height);

void gtk_window_set_policy (GtkWindow *window,
                            gint allow_shrink,
                            gint allow_grow,
                            gint auto_shrink);
</PRE>
</CODE></BLOCKQUOTE>
<P><CODE>Auto_shrink</CODE> will automatically shrink the window when the
requested size of the child widgets goes below the current size of the
window. <CODE>Allow_shrink</CODE> will give the user the authorisation to make
the window smaller that it should normally be. <CODE>Allow_grow</CODE> will
give the user will have the ability to make the window bigger. The
default values for these parameters are:
<P>
<BLOCKQUOTE><CODE>
<PRE>
allow_shrink = FALSE
allow_grow   = TRUE
auto_shrink  = FALSE
</PRE>
</CODE></BLOCKQUOTE>
<P>The <CODE>gtk_widget_set_usize()</CODE> functions is not the easiest way to
set a window size since you cannot decrease this window size with
another call to this function unless you call it twice, as in:
<P>
<BLOCKQUOTE><CODE>
<PRE>
     gtk_widget_set_usize(your_widget, -1, -1);
     gtk_widget_set_usize(your_widget, new_x_size, new_y_size);
</PRE>
</CODE></BLOCKQUOTE>
<P>Another way to set the size of and/or move a window is to use the
<CODE>gdk_window_move_resize()</CODE> function which uses to work fine both to
grow or to shrink the window:
<P>
<BLOCKQUOTE><CODE>
<PRE>
     gdk_window_move_resize(window->window, 
                            x_pos, y_pos, 
                            x_size, y_size);
</PRE>
</CODE></BLOCKQUOTE>
<P>
<H2><A NAME="ss5.20">5.20 How do I add a popup menu to my GTK+ application?</A>
</H2>

<P>The <CODE>menu</CODE> example in the examples/menu directory of the GTK+ distribution
implements a popup menu with this technique :
<P>
<BLOCKQUOTE><CODE>
<PRE>
static gint button_press (GtkWidget *widget, GdkEvent *event)
{

    if (event->type == GDK_BUTTON_PRESS) {
        GdkEventButton *bevent = (GdkEventButton *) event; 
        gtk_menu_popup (GTK_MENU(widget), NULL, NULL, NULL, NULL,
                        bevent->button, bevent->time);
        /* Tell calling code that we have handled this event; the buck
         * stops here. */
        return TRUE;
    }

    /* Tell calling code that we have not handled this event; pass it on. */
    return FALSE;
}
</PRE>
</CODE></BLOCKQUOTE>
<P>
<H2><A NAME="ss5.21">5.21 How do I disable or enable a widget, such as a button?</A>
</H2>

<P>To disable (or to enable) a widget, use the
<CODE>gtk_widget_set_sensitive()</CODE> function. The first parameter is you
widget pointer. The second parameter is a boolean value: when this
value is TRUE, the widget is enabled.
<P>
<H2><A NAME="ss5.22">5.22 Shouldn't the text argument in the gtk_clist_* functions be declared const?</A>
</H2>

<P>For example:
<PRE>
gint gtk_clist_prepend (GtkCList *clist,
                        gchar    *text[]);
</PRE>
<P>Answer: No, while a type "gchar*" (pointer to char) can automatically
be cast into "const gchar*" (pointer to const char), this does not
apply for "gchar *[]" (array of an unspecified number of pointers to
char) into "const gchar *[]" (array of an unspecified number of
pointers to const char).
<P>The type qualifier "const" may be subject to automatic casting, but in
the array case, it is not the array itself that needs the (const)
qualified cast, but its members, thus changing the whole type.
<P>
<H2><A NAME="ss5.23">5.23 How do I render pixels (image data) to the screen?</A>
</H2>

<P>There are several ways to approach this. The simplest way is to use
GdkRGB, see gdk/gdkrgb.h. You create an RGB buffer, render to your RGB
buffer, then use GdkRGB routines to copy your RGB buffer to a drawing
area or custom widget. The book "GTK+/Gnome Application Development"
gives some details; GdkRGB is also documented in the GTK+ reference
documentation.
<P>If you're writing a game or other graphics-intensive application, you
might consider a more elaborate solution. OpenGL is the graphics
standard that will let you access hardware accelaration in future
versions of XFree86; so for maximum speed, you probably want to use
OpenGL. A GtkGLArea widget is available for using OpenGL with GTK+
(but GtkGLArea does not come with GTK+ itself). There are also several
open source game libraries, such as ClanLib and Loki's Simple
DirectMedia Layer library (SDL).
<P>You do NOT want to use <CODE>gdk_draw_point()</CODE>, that will be extremely
slow.
<P>
<H2><A NAME="ss5.24">5.24 How do I create a pixmap without having my window realized/shown?</A>
</H2>

<P>Functions such as <CODE>gdk_pixmap_create_from_xpm()</CODE> require a valid
window as a parameter. During the initialisation phase of an
application, a valid window may not be available without showing a
window, which may be inappropriate. In order to avoid this, a
function such as <CODE>gdk_pixmap_colormap_create_from_xpm</CODE> can be used,
as in:
<P>
<BLOCKQUOTE><CODE>
<PRE>
  char *pixfile = "foo.xpm";
  GtkWidget *top, *box, *pixw;
  GdkPixmap *pixmap, *pixmap_mask;

  top = gtk_window_new (GKT_WINDOW_TOPLEVEL);
  box = gtk_hbox_new (FALSE, 4);
  gtk_conainer_add (GTK_CONTAINER(top), box);
 
  pixmap = gdk_pixmap_colormap_create_from_xpm (
               NULL, gtk_widget_get_colormap(top),
               &amp;pixmap_mask, NULL, pixfile);
  pixw = gtk_pixmap_new (pixmap, pixmap_mask);
  gdk_pixmap_unref (pixmap);
  gdk_pixmap_unref (pixmap_mask);
</PRE>
</CODE></BLOCKQUOTE>
<P>
<HR NOSHADE>
<A HREF="gtkfaq-6.html">Next</A>
<A HREF="gtkfaq-4.html">Previous</A>
<A HREF="gtkfaq.html#toc5">Contents</A>
</BODY>
</HTML>