File: es.mo

package info (click to toggle)
gtkmm-documentation 3.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 18,628 kB
  • ctags: 2,376
  • sloc: cpp: 12,615; sh: 1,004; makefile: 808; perl: 57
file content (2109 lines) | stat: -rw-r--r-- 654,283 bytes parent folder | download | duplicates (3)
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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
d5j0R1ekdVq-~tou]y[ה%3UY2ڙ>XA`ٛI:.t19p2dU(~S37۬}j[pDC}pc2gKJz3\QMEܹ2"-USC׺ZavUػq.:ۼA$H#Bl;'=PQ.(ѿ(I#\m3de466A?aO7rRP5\B@_E)H:&
5@G$]45:.wX*JTua,/GwudY-@n!F.ua$,	Y^z3rCJ		
IO

O:$/8wStsZ799s\  } !np"#e$CX%&qt'(x* *,--j./01C33ze4^5Z?6=6R6=+7i7s<2<>rZ@eA3BCC/DDEpF)H~I.JK$L4MxNNWDOCP2PQQXSmT+Th U$UUtVKWQWh8Y+Y3Y.ZT0\Y\\]q(^n^	__oR`l`/aaSCbGd_d-?efmeOe$fh}i/jv6jj4k+k m4m1nrEopYrtUt](ujuuzv;gww|xCSyIz}q~bY0I(wrtaH~.F.
6D'͔(ҕΖ}y'G;,`8I		9Ǩ=?]Ǯ8ʰswMGн;
)	=@
,O:SQis/	;&El;t+$$2+M^xt%kN

2^'!	LVbgjX\Xu+;R<I;I-4b "%Ci.
	{&
*AN(f@'	GQdq"'/L^zy
PW]=RL
=	!&	H	(

vts{r

~
/I^m!`*Y&{=AHD0?0G#x$:>;ARk~
0#
2@[dp9'* ^<  \d#i#E+$Iq$C%M%M&
'%'(I)Je)J)w)Es*G*C+FE+I+F+B,B`,C,C,-+-Y-
.e..Ve/Y011124444q6M7B8^8y8+88[t:::":!<R8<l<\<NU=T==k>&?X@A|!BXBBmCaDTEYFxF
;G IG\jGGBJKKLL)MMwM;NXNJOO PRR3cT TtTB-U<pVoVTWSrWwXm>Y6YYYZ.Z[/[
;[/I[y[7S\(\\7]_]#P^t^;-_i_v`aa)c4dCAdBded$.enSef$f#fhbi'Ylm4$n$Yoo~o!oqqr$*rOt)(uQRvwo5xy<{|r}@@*kDjŇ$0U	c|^?jO-B6pImRW&Ț^.Cr
FT
r,ƫSӫ'H>"%%	:&\a=1.aQF	`jsb{d޵C#Sw%Ƿڷ'b%HѸo;	%,=3j	ܾ̾v5;A

*@
Vd".Q`*(A(7x}zWCe2=4rMop'G_hw,mc'vvO
	o]Y&	Q-FLdxhtV"r3m
u=C+X,
1aH3%)o
~
z!	




	%+/[B
	2JQ!^
?	vLpb{6]F*
[Qiq$9"Hk
Q( !"#B$J$}&'yB))(+I,-12262B2[22q4
4m4
56!7799999>9N:@;;;t=Q@Z@oBBVC.DEDEFG8HIJHKPM=gObPQYQT_T`UNbUW?XXYZ[]]`]D`7abEcndvd.e{e0hhUi2jejn$o9qrasz(t
ttu?wWw
xy	y%y
=yKyZ_yyyzy{{~||9|}6`~4~~p	Xbr<aN	9WCA9{
Wȍm mRMߖOEʛLg{xB=7u4G|	*40s) N̬c`\Dx@NG״T]	uNJķC!neԻJw¾`pJ0W}
|Yt3&Qjx]{QjD8}a/?9A576D9{m#;cM(iD	N6kQH	RTW
C9sj@#d[6:c^R}Cne3		D
7
2&XY8L
d
U47;Fd$~w;as9A[va\pY/!"&#k#$r$n0%& &h&32(wf))*l++,G-/.;/BD012k5(6E7889w:
;<<\>|>?f?@iDA3ACYDEFAG=H/JrHKMN7}OPPPPPQQ2Q:QLQUQ1SSS	TT)TBT\TqTTiTUNUU@V		WW90Wj[y[__
`a?aXaYb`b/d'eHfbYffcghhiii/j
2j@j%Vj9|jjjflEmnpoSqlr-rs*]t,uufv/wwxyz|~}y{M@Ƀ
҅UDJD q90A7?YIrS 1!1Sk~
 ĠeirU0'X\/zt	ƱR۴u[A>R!y-]@~.cxroV)UQ~:f	MHRW-o$S4UE?XVZ
#191R4)/+[)w7!3//7_3

4Q'h):3Q :.7=J! P
dv
+.#)2O	>(1
8CKZ_dk
^fj$
&54H;}%9a4{e2*]ie)"F/vy

D>#	p	
7xR	'
2
:	HRk:

d 3T0gD
Qpb%mr0R^ekdqZ~  !!"u0#]#[$%`$U$2&())>{*A*`*I]++=,..40tT11\23p42567UK88)9S:3&;Z;;}<[=pg==>A?@C@p@cUAgAK!BmBzC3CQEFGpHEH2EI-xISICIZ>JaJUJqQK:KKAL$!MHFMBM;M'N=6NPtN.N(N(OIFO\OO3P4PPdS4S6"UYV<WA XbXXaYrYZ
[7[r\u\P.]5]]_`Bca_bEcLcHacccMd
\dgdtgG:hhKi]j4^jj8kB+lnlN@mnGq(^rdrsu-x1xy"{}l}1>CVك^NVn:bS6ڗp}TÜoY_]Z8A,X
ݮ_aL|cɲ-`״98rP!f^ռu 2sYYl`BY0F*qpng!DV%^=7sjV8D5
#Uy1P'q12NX3fj#fj%fnGog-aMLtG/ub>q##(	2;	#
Qdkb{6Z
ZD-=$A^	h -P#M~&&n(j)*Q,,.F....//////&0900211111333i44	45
89
-;;="=i>(_??\@
AeB\F	eFDoF[GII/K!KLTO[QTUVkWXYJ[]g^%M`7sab	bbdSeg"gGh CjdjzvjlmoxpRstw	w*wwwSx78z,p{{{{Q{R.}z~~B'@-n/	lxhbpӉ^BK’	
$?2rm-#*7&!^+*@ט,E^x6<Xi}ܛ +'SBk  Ϝ&
"
:H]
$+ 3Tǧקܨ&=ԩ۩?hfrM	ԬLެ+#	#-#Q
uF"/:j0yɵ+"Be|
ʶ!v&8&ַtE
>P."ؿ#CLc"# 9Z:Nn}0&
"<EZl?5ob^j/C`C?MIJCJ}DWD@C"FfC??1@q@4(zmTb;"("+KdA"6\)vb``a#kPXE|KX!ma~YH
es\B!\(1;\ 3 t(B<oTSw6m6-S-y29$An9,	f	A%
g
/*
%@IfHMlG~P(g:d1#U^$co! 0JD X!="2$$L&'(*L-R-.X013i5M6E98:K<>e?rn??@uA,CB-D6pDD_EVFiFQG!HIJK@L+M5OOQRTsWyXYYZ4ZZZ[	\P\g\J\I\^%)^'O^w^
^?^q^qJ`=abc3d$e!f
?fJfSfh[fjf/g+Bgngggg<ghh!h*igEiEiijk
ln	nn
o2&oUYoppppqr|sssstuu
uuuuuv)v=v#v(w>wNw6w+
x9z/3|c|\}J}/5Sru|`IO>@9z$r3}DŒ"3V`cЕbk$Sx,I5Oms*Kv¦֨Gڨ{"\{#Y0Kv"^2
3¶÷Ϸ9Ÿ117 =&^	y#ڼ0aEǽԽ
0C

+A


8+4!=	D&Nu#o*w9gk7Aul0'(
o OI6394y&Ow!r)
IkT1			q\0$5ZO$tnE;>Z
1
?
Rv*g_fg`/C@	afg!"~$%%s&H''*|+pm,,t-	2?45d6<7	7$78::<<	<<<<j
=u=&~=>M??t@@8@AAwB?B<Bo6D1DFF:G,HK
MQNRO=O;PQjRy2TvT#U)VWJX,YYZH\]]^aabcwdIeDf?9gygJkij	kk7rllOnopisj3tt]yuuhwyuyJ{d|W|$M}
r~}~SIYIֈZQV]cɑi:7Krr1Au7KF0~3>?1D3xIV45u'c5iPt/.v@
͹Qع*Ǽ?F1_7x":NK;CwF|Bvx~[ |p46k O!Fq2f0RJIg(O=cbft>lB?DKW&~wyoRvt},:@{OL	c	A	@	S	5	N		
	
			J
	R			Z	d	D	x	zg		h	6		 		9		!	t"	Z\#	$	$	$	$	%	%	3%	M%	U%	l%	u%	o'	(	/(		J(	T(	s(	(	(	%(	(	p(	l)	K*	Z*	ZW+		+	$+	q+	S0	`0	4	
5	6	/6	@L6	6	VJ7	7	9	:	R;	f;	Y<	=	=	#>	?	 ?	@	2@	N@	]@	#t@	;@	@	@	B	~C	FE	UF	G	sH	BCI	J	4>K	,sL	8L	[M	5N	N	
P	
Q	@Q	:T	'V	~ W	W	xX	(Y	![	~[	%]	0]	S)a	}b	:c	f	h	9i	Tl	@l	m	,m	n	&n	<n	rSn	p	'~t	
t	"v	 v	$v	w	3w	 w	x	z	z	~{	m{	m|	|	}	u~	D	a<		V	L	6		j	`g	Ȋ		=			t	A			gW		w	L	&			Ù		ڜ	T	 	6	à		[	#		H		}w		T	װ	Ȳ	']						w	W			OX		ƾ	s	d	r)		nB		^		R	L	-d		$		S	)	U:				4	XK		Z	
	&	.	1G	4y			)		/ 	P	)l	7	!	3	/$	7T	3		
	
				4	F	']		)		:		3	F	 	1		"	(	5			!					 			P						R	d	{		
	+	.		
				<			>		 	
'	2	:	L	Q	V	#]	
											e	f	j	$				
	&	6	4M	;	%	9	a	4	e		2/	b	ij		)		'	K4			
			D	>	-	p	 	7$	x\						'	<	
E		S	]	v	E				d	.\		0E	
v	U		
		Qc	b			`				0	O[j0vp/H>0*GLA=Fz!Y_?1]bSfL/O@dk$G`zM%7Orrq@)F&2%m{lE^e	w\YMj&4;_v+tqy\}$(W$rf rt.A>+A5vBxGC+aTE@?p>JG
XZp-<f>D
Y
h$o5d[teQ`t3ZWwqqWMub2isXwpAD,L`7s(Wfg8Y|IYPy1Z);!O]#W`K=Cc'hUY	4^9j^UHvHof,|?nL)u;Nu:h_~n>.LF[~,?::yShEOc'w_Z,3Uc#"/ ,*Z48Q@RSa%py7!6#9r/-w=1Q
Ig1)~UH
4$:O+99Pboei&BsKilMICgl,S}cJ(
)a-]13cZTN:	P2F;8}E
\TdX^|j%f84{2[U$|mz%YiD&+aGF15k=|R8!~C5G?	0eg
iV(+
lm6=
JD67qR]g#x;<=MB*g6P.|pTka%TN~;*R	ZJozBfM_^$7[z#P#k_	*!sLhwgJBB

V*}R x !GjK 
Tu0;PXwd.F"0q0KHCe3/Hun}]vU&9.<xQ6'(}!V{ksIc/vQxm87SC<y1lc:\-):`R4'F{{2&tjN@VaN#jvQIQXDs 2e53A{_hqn-^X=Kb.o \do&Wb[]xzs
diKU+y65*',Au	t>iS@0~-u"nNMP"8dCKB(5b?nS"%R\lO`"69\Ntml^"('}XL]V27@>)3VrnHm[.Eke~hJJ<|{bAIk3paDWxE<E9T/-'z`<DyI4omV?r
        GtkSizeRequestMode gtk_widget_get_request_mode(GtkWidget* widget);
      
        GtkToolItem* gtk_tool_button_new(GtkWidget* icon_widget, const gchar*
        label);
      
        _INITIALIZATION(`Gdk::Rectangle&amp;',`GdkRectangle', `$3 =
        Glib::wrap(&amp;($4))')
      
        _INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 =
        ($1)($4)')
      
        _INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 =
        (SizeRequestMode)($4)')
      
        _WRAP_CTOR(ToolButton(Widget&amp; icon_widget, const Glib::ustring&amp;
        label{?}), gtk_tool_button_new)
      
        _WRAP_METHOD(bool get_cell_rect(const TreeModel::Path&amp; path, const
        CellRenderer&amp; cell, Gdk::Rectangle&amp; rect{&gt;&gt;}) const,
        gtk_icon_view_get_cell_rect)
      
        _WRAP_METHOD(void get_request_mode(SizeRequestMode&amp; mode{OUT})
        const, gtk_widget_get_request_mode)
      
        _WRAP_METHOD(void set_device_events(Gdk::EventMask events{.}, const
        Glib::RefPtr&lt;const Gdk::Device&gt;&amp; device{.}),
        gtk_widget_set_device_events)
      
        _WRAP_METHOD(void set_device_events(Gdk::EventMask events{events},
        const Glib::RefPtr&lt;const Gdk::Device&gt;&amp; device{device}),
        gtk_widget_set_device_events)
      
        gboolean gtk_icon_view_get_cell_rect(GtkIconView* icon_view,
        GtkTreePath* path, GtkCellRenderer* cell, GdkRectangle* rect);
      
        void gtk_widget_set_device_events(GtkWidget* widget, GdkDevice* device,
        GdkEventMask events);
      
    ...
    button.signal_clicked().connect(sigc::ptr_fun(&amp;on_button_clicked));
    ...

  $ git clone git://git.gnome.org/mm-common
  $ cp -a mm-common/skeletonmm libsomethingmm

# ./configure
# make
# make install

#include &lt;gtkmm/bin.h&gt;
#include &lt;gtkmm/activatable.h&gt;
_DEFS(gtkmm,gtk)
_PINCLUDE(gtkmm/private/bin_p.h)

namespace Gtk
{

class Button
  : public Bin,
    public Activatable
{
  _CLASS_GTKOBJECT(Button,GtkButton,GTK_BUTTON,Gtk::Bin,GtkBin)
  _IMPLEMENTS_INTERFACE(Activatable)
public:

  _CTOR_DEFAULT
  explicit Button(const Glib::ustring&amp; label, bool mnemonic = false);

  _WRAP_METHOD(void set_label(const Glib::ustring&amp; label), gtk_button_set_label)

  ...

  _WRAP_SIGNAL(void clicked(), "clicked")

  ...

  _WRAP_PROPERTY("label", Glib::ustring)
};

} // namespace Gtk

#include &lt;gtkmm/button.h&gt;

class OverriddenButton : public Gtk::Button
{
protected:
    virtual void on_clicked();
}

void OverriddenButton::on_clicked()
{
    std::cout &lt;&lt; "Hello World" &lt;&lt; std::endl;

    // call the base class's version of the method:
    Gtk::Button::on_clicked();
}

#include &lt;gtkmm/button.h&gt;

void on_button_clicked()
{
    std::cout &lt;&lt; "Hello World" &lt;&lt; std::endl;
}

main()
{
    Gtk::Button button("Hello World");
    button.signal_clicked().connect(sigc::ptr_fun(&amp;on_button_clicked));
}

#include &lt;gtkmm/button.h&gt;
#include &lt;gtkmm/window.h&gt;
class Foo : public Gtk::Window
{
private:
  Gtk::Button theButton;
  // will be destroyed when the Foo object is destroyed
};

#include &lt;libsomething.h&gt;

int main(int, char**)
{
  something_init();

  std::cout &lt;&lt; get_defs(SOME_TYPE_WIDGET)
            &lt;&lt; get_defs(SOME_TYPE_STUFF);
  return 0;
}

$ ./enum.pl /usr/include/gtk-3.0/gtk/*.h &gt; gtk_enums.defs

$ ./h2def.py /usr/include/gtk-3.0/gtk/*.h &gt; gtk_methods.defs

$ cd gtk/src
$ /usr/lib/glibmm-2.4/proc/gmmproc -I ../../tools/m4 --defs . button . ./../gtkmm

$ cd tools/extra_defs_gen
$ ./generate_extra_defs &gt; gtk_signals.defs

$ for f in $(find libsomethingmm -depth -name '*skeleton*'); do \
    d="${f%/*}"; b="${f##*/}"; mv "$f" "$d/${b//skeleton/libsomething}"; \
  done

&gt; gdb with_signal
(gdb) catch throw
Catchpoint 1 (throw)
(gdb) run
Catchpoint 1 (exception thrown), 0x00714ff0 in __cxa_throw ()
(gdb) backtrace
#0  0x00714ff0 in __cxa_throw () from /usr/lib/i386-linux-gnu/libstdc++.so.6
#1  0x08048bd4 in throwSomething () at with_signal.cc:6
(gdb) continue
Continuing.
(with_signal:2375): glibmm-ERROR **
unhandled exception (type unknown) in signal handler

Program received signal SIGTRAP, Trace/breakpoint trap.

&gt; gdb with_signal
(gdb) run
(with_signal:2703): glibmm-ERROR **:
unhandled exception (type unknown) in signal handler

Program received signal SIGTRAP, Trace/breakpoint trap.
(gdb) backtrace
#2  0x0063c6ab in glibmm_unexpected_exception () at exceptionhandler.cc:77
#3  Glib::exception_handlers_invoke () at exceptionhandler.cc:150
#4  0x0063d370 in glibmm_source_callback (data=0x804d620) at main.cc:212
#13 0x002e1b31 in Gtk::Application::run (this=0x804f300) at application.cc:178
#14 0x08048ccc in main (argc=1, argv=0xbfffecd4) at with_signal.cc:16

&gt; gdb without_signal
(gdb) run
terminate called after throwing an instance of 'char const*'

Program received signal SIGABRT, Aborted.
(gdb) backtrace
#7  0x08048864 in throwSomething () at without_signal.cc:6
#8  0x0804887d in main (argc=1, argv=0xbfffecd4) at without_signal.cc:12

(gdb) catch throw
(gdb) commands
(gdb)   backtrace
(gdb)   continue
(gdb)   end
(gdb) set pagination off
(gdb) run

// _MEMBER_GET_PTR(engine_lang, lang_engine, EngineLang*, PangoEngineLang*)
// It's just a comment. It's difficult to find a real-world example.

// in a class that inherits from Gtk::Window...
Glib::RefPtr&lt;PrintOperation&gt; op = PrintOperation::create();
// ...set up op...
op-&gt;run(Gtk::PRINT_OPERATION_ACTION_PREVIEW, *this);

// in class ExampleWindow's method...
Glib::RefPtr&lt;PrintOperation&gt; op = PrintOperation::create();
// ...set up op...
op-&gt;signal_done().connect(sigc::bind(sigc::mem_fun(*this, &amp;ExampleWindow::on_printoperation_done), op));
// run the op

// with_signal.cc
#include &lt;gtkmm.h&gt;

bool throwSomething()
{
  throw "Something";
  return true;
}

int main(int argc, char** argv)
{
  Glib::signal_timeout().connect(sigc::ptr_fun(throwSomething), 500);
  Glib::RefPtr&lt;Gtk::Application&gt; app =
    Gtk::Application::create(argc, argv, "org.gtkmm.with_signal");
  app-&gt;hold();
  return app-&gt;run();
}

// without_signal.cc
#include &lt;gtkmm.h&gt;

bool throwSomething()
{
  throw "Something";
  return true;
}

int main(int argc, char** argv)
{
  throwSomething();
  Glib::RefPtr&lt;Gtk::Application&gt; app =
    Gtk::Application::create(argc, argv, "org.gtkmm.without_signal");
  return app-&gt;run();
}

//Within a class that inherits from Gtk::Window and keeps m_refPageSetup and m_refSettings as members...
Glib::RefPtr&lt;Gtk::PageSetup&gt; new_page_setup = Gtk::run_page_setup_dialog(*this, m_refPageSetup, m_refSettings);
m_refPageSetup = new_page_setup;

Button::Button(const Glib::ustring&amp; label, bool mnemonic)
:
  _CONSTRUCT("label", label.c_str(), "use_underline", gboolean(mnemonic))
{}

DerivedDialog* pDialog = 0;
builder-&gt;get_widget_derived("DialogBasic", pDialog);

DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder)
: Gtk::Dialog(cobject)
{
}

DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder)
: Gtk::Dialog(cobject),
  m_builder(builder),
  m_pButton(0)
{
  //Get the Glade-instantiated Button, and connect a signal handler:
  m_builder-&gt;get_widget("quit_button", m_pButton);
  if(m_pButton)
  {
    m_pButton-&gt;signal_clicked().connect( sigc::mem_fun(*this, &amp;DerivedDialog::on_button_quit) );
  }
}

Glib::RefPtr&lt;Gdk::Pixbuf&gt; pixbuf = Gdk::Pixbuf::create_from_file(filename);

Glib::RefPtr&lt;Gdk::Pixbuf&gt; pixbuf2 = pixbuf;

Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
Gdk::Pixbuf&amp; underlying = *refPixbuf; //Syntax error - will not compile.

Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf2 = refPixbuf;

Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
int width = refPixbuf-&gt;get_width();

Glib::RefPtr&lt;Gtk::Builder&gt; builder = Gtk::Builder::create_from_file("basic.glade");

Glib::RefPtr&lt;Gtk::Builder&gt; builder = Gtk::Builder::create_from_file("basic.glade", "treeview_products");

Glib::RefPtr&lt;Gtk::PrintOperation&gt; op = Gtk::PrintOperation::create();
// ...set up op...
op-&gt;set_export_filename("test.pdf");
Gtk::PrintOperationResult res = op-&gt;run(Gtk::PRINT_OPERATION_ACTION_EXPORT);

Glib::RefPtr&lt;Gtk::TreeModel&gt; refModel = m_TreeView.get_model();
if(refModel)
{
  int cols_count = refModel-&gt;get_n_columns();
  ...
}

Glib::RefPtr&lt;Gtk::TreeStore&gt; refStore =
Glib::RefPtr&lt;Gtk::TreeStore&gt;::cast_dynamic(refModel);
Glib::RefPtr&lt;Gtk::TreeStore&gt; refStore2 =
Glib::RefPtr&lt;Gtk::TreeStore&gt;::cast_static(refModel);

Glib::RefPtr&lt;Gtk::TreeStore&gt; refStore = Gtk::TreeStore::create(columns);
Glib::RefPtr&lt;Gtk::TreeModel&gt; refModel = refStore;

Glib::SignalProxy1&lt;bool, Gtk::DirectionType&gt; signal_focus()

Glib::SignalProxy3&lt;void, const TextBuffer::iterator&amp;, const Glib::ustrin&amp;, int&gt; signal_insert();

Gtk::Button* button = new Gtk::Button("example");
gtk_button_do_something_new(button-&gt;gobj());

Gtk::Button* pButton = new Gtk::Button("Test");

// do something useful with pButton

delete pButton;

Gtk::Dialog* pDialog = 0;
builder-&gt;get_widget("DialogBasic", pDialog);

Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton(icon, "Big"));
button-&gt;set_tooltip_text("Big Brush);
group_brushes-&gt;insert(*button);

Gtk::ToolItemGroup* group_brushes =
  Gtk::manage(new Gtk::ToolItemGroup("Brushes"));
m_ToolPalette.add(*group_brushes);

Gtk::Widget* CustomPrintOperation::on_create_custom_widget()
{
  set_custom_tab_label("My custom tab");

  Gtk::Box* hbox = new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 8);
  hbox-&gt;set_border_width(6);

  Gtk::Label* label = Gtk::manage(new Gtk::Label("Enter some text: "));
  hbox-&gt;pack_start(*label, false, false);
  label-&gt;show();

  hbox-&gt;pack_start(m_Entry, false, false);
  m_Entry.show();

  return hbox;
}

void CustomPrintOperation::on_custom_widget_apply(Gtk::Widget* /* widget */)
{
  Glib::ustring user_input = m_Entry.get_text();
  //...
}

GtkButton* cbutton = get_a_button();
Gtk::Button* button = Glib::wrap(cbutton);

GtkWidget* example_widget_new(int something, const char* thing)
{
        ExampleWidget* widget;
        widget = g_object_new (EXAMPLE_TYPE_WIDGET, NULL);
        example_widget_construct(widget, "something", something, "thing", thing);
}

void example_widget_construct(ExampleWidget* widget, int something, const char* thing)
{
        //Do stuff that uses private API:
        widget-&gt;priv-&gt;thing = thing;
        do_something(something);
}

GtkWidget* example_widget_new(int something, const char* thing)
{
        return g_object_new (EXAMPLE_TYPE_WIDGET, "something", something, "thing", thing, NULL);
}

MyContainer::MyContainer()
{
  Gtk::Button* pButton = Gtk::manage(new Gtk::Button("Test"));
  add(*pButton); //add *pButton to MyContainer
}

_CLASS_BOXEDTYPE(RGBA, GdkRGBA, NONE, gdk_rgba_copy, gdk_rgba_free)

_CLASS_BOXEDTYPE_STATIC(Rectangle, GdkRectangle)

_CLASS_GENERIC(AttrIter, PangoAttrIterator)

_CLASS_GOBJECT(AccelGroup, GtkAccelGroup, GTK_ACCEL_GROUP, Glib::Object, GObject)

_CLASS_GTKOBJECT(Button, GtkButton, GTK_BUTTON, Gtk::Bin, GtkBin)

_CLASS_INTERFACE(CellEditable, GtkCellEditable, GTK_CELL_EDITABLE, GtkCellEditableIface)

_CLASS_INTERFACE(LoadableIcon, GLoadableIcon, G_LOADABLE_ICON, GLoadableIconIface, Icon, GIcon)

_CLASS_OPAQUE_COPYABLE(Checksum, GChecksum, NONE, g_checksum_copy, g_checksum_free)

_CLASS_OPAQUE_REFCOUNTED(Coverage, PangoCoverage, pango_coverage_new, pango_coverage_ref, pango_coverage_unref)

_CONVERSION(`GtkTreeView*',`TreeView*',`Glib::wrap($3)')

_CONVERSION(`PrintSettings&amp;',`GtkPrintSettings*',__FR2P)
_CONVERSION(`const PrintSettings&amp;',`GtkPrintSettings*',__FCR2P)
_CONVERSION(`const Glib::RefPtr&lt;Printer&gt;&amp;',`GtkPrinter*',__CONVERT_REFPTR_TO_P($3))

_IGNORE(gtk_button_box_set_spacing, gtk_button_box_get_spacing)

_IMPLEMENTS_INTERFACE(Activatable)

_INITIALIZATION(`Gtk::Widget&amp;',`GtkWidget*',`$3 = Glib::wrap($4)')

_MEMBER_GET_GOBJECT(layout, layout, Pango::Layout, PangoLayout*)

_WRAP_ENUM(IconLookupFlags, GtkIconLookupFlags, NO_GTYPE)

_WRAP_ENUM(WindowType, GtkWindowType)

_WRAP_GERROR(PixbufError, GdkPixbufError, GDK_PIXBUF_ERROR)

_WRAP_METHOD(void set_text(const Glib::ustring&amp; text), gtk_entry_set_text)

_WRAP_METHOD_DOCS_ONLY(gtk_container_remove)

_WRAP_PROPERTY("label", Glib::ustring)

_WRAP_SIGNAL(void clicked(),"clicked")

_WRAP_VFUNC(SizeRequestMode get_request_mode() const, get_request_mode)

bool MyCallback() { std::cout &lt;&lt; "Hello World!\n" &lt;&lt; std::endl; return true; }

bool idleFunc();

bool input_callback(Glib::IOCondition condition);

bool on_button_press(GdkEventButton* event);
Gtk::Button button("label");
button.signal_button_press_event().connect( sigc::ptr_fun(&amp;on_button_press) );

bool on_key_press_or_release_event(GdkEventKey* event)
{
  if (event-&gt;type == GDK_KEY_PRESS &amp;&amp;
    event-&gt;keyval == GDK_KEY_1 &amp;&amp;
    (event-&gt;state &amp; (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK)) == GDK_MOD1_MASK)
  {
    handle_alt_1_press(); // GDK_MOD1_MASK is normally the Alt key
    return true;
  }
  return false;
}

Gtk::Entry m_entry; // in a class definition

// in the class constructor
m_entry.signal_key_press_event().connect( sigc::ptr_fun(&amp;on_key_press_or_release_event) );
m_entry.signal_key_release_event().connect( sigc::ptr_fun(&amp;on_key_press_or_release_event) );
m_entry.add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);

button.signal_button_press_event().connect( sigc::ptr_fun(&amp;on_mywindow_button_press), false );

class Server
{
public:
  //signal accessor:
  typedef sigc::signal&lt;void, bool, int&gt; type_signal_something;
  type_signal_something signal_something();

protected:
  type_signal_something m_signal_something;
};

Server::type_signal_something Server::signal_something()
{
  return m_signal_something;
}

class TextMark : public Glib::Object
{
  _CLASS_GOBJECT(TextMark, GtkTextMark, GTK_TEXT_MARK, Glib::Object, GObject)

protected:
  _WRAP_CTOR(TextMark(const Glib::ustring&amp; name, bool left_gravity = true), gtk_text_mark_new)

public:
  _WRAP_CREATE(const Glib::ustring&amp; name, bool left_gravity = true)

example-widget.h:56: error: using typedef-name 'ExampleWidget' after 'struct'
../../libexample/libexamplemm/example-widget.h:34: error: 'ExampleWidget' has a previous declaration here
make[4]: *** [example-widget.lo] Error 1

example-widget.h:60: error: '_ExampleWidget ExampleWidget' redeclared as different kind of symbol
../../libexample/libexamplemm/example-widget.h:34: error: previous declaration of 'typedef struct _ExampleWidget ExampleWidget'

int width = 0;
if(pixbuf)
{
  width = pixbuf-&gt;get_width();
}

m_button1.signal_clicked().connect( sigc::bind&lt;Glib::ustring&gt;( sigc::mem_fun(*this, &amp;HelloWorld::on_button_clicked), "button 1") );

my_connection.disconnect();

server.signal_something().connect(
  sigc::mem_fun(client, &amp;Client::on_server_something) );

sigc::connection  Glib::SignalIdle::connect(const sigc::slot&lt;bool&gt;&amp; slot,
                                    int priority = Glib::PRIORITY_DEFAULT_IDLE);

sigc::connection Glib::SignalIO::connect(const sigc::slot&lt;bool,Glib::IOCondition&gt;&amp; slot,
                                 int fd, Glib::IOCondition condition,
                                 int priority = Glib::PRIORITY_DEFAULT);

sigc::connection Glib::SignalTimeout::connect(const sigc::slot&lt;bool&gt;&amp; slot,
                                      unsigned int interval, int priority = Glib::PRIORITY_DEFAULT);

sigc::signal&lt;void, bool, int&gt; signal_something;

sigc::signal&lt;void,int&gt;::iterator signal&lt;void,int&gt;::connect( const sigc::slot&lt;void,int&gt;&amp; );

std::list&lt; Glib::RefPtr&lt;Gdk::Pixbuf&gt; &gt; listPixbufs;
Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
listPixbufs.push_back(refPixbuf);

typedef struct _ExampleWidget ExampleWidget;

struct _ExampleWidget
{
  ...
};

virtual void on_button_clicked(Glib::ustring data);

void ExampleWindow::on_printoperation_done(Gtk::PrintOperationResult result, const Glib::RefPtr&lt;PrintOperation&gt;&amp; op)
{
  if (result == Gtk::PRINT_OPERATION_RESULT_ERROR)
    //notify user
  else if (result == Gtk::PRINT_OPERATION_RESULT_APPLY)
    //Update PrintSettings with the ones used in this PrintOperation

  if (! op-&gt;is_finished())
    op-&gt;signal_status_changed().connect(sigc::bind(sigc::mem_fun(*this, &amp;ExampleWindow::on_printoperation_status_changed), op));
}

void ExampleWindow::on_printoperation_status_changed(const Glib::RefPtr&lt;PrintFormOperation&gt;&amp; op)
{
  if (op-&gt;is_finished())
    //the print job is finished
  else
    //get the status with get_status() or get_status_string()

  //update UI
}

void init()
{
  Gtk::Main::init_gtkmm_internals(); //Sets up the g type system and the Glib::wrap() table.
  wrap_init(); //Tells the Glib::wrap() table about the libsomethingmm classes.
}

void on_button_clicked();

class some_class
{
    void on_button_clicked();
};

some_class some_object;

main()
{
    Gtk::Button button;
    button.signal_clicked().connect( sigc::ptr_fun(&amp;on_button_clicked) );
    button.signal_clicked().connect( sigc::mem_fun(some_object, &amp;some_class::on_button_clicked) );
}

void on_insert(const TextBuffer::iterator&amp; pos, const Glib::ustring&amp; text, int bytes)

{
  Gtk::Button aButton;
  aButton.show();
  ...
  app-&gt;run();
}
"Hidden" Columns# keep this file sorted alphabetically, one language code per line
de
ja#include &lt;gtkmm.h&gt;#m4 _CONVERSION(`GSList*',`std::vector&lt;Widget*&gt;',`Glib::SListHandler&lt;Widget*&gt;::slist_to_vector($3, Glib::OWNERSHIP_SHALLOW)')$ ./plug &amp;$ ./socket(An aside: <application>GTK+</application> calls this scheme "signalling"; the sharp-eyed reader with GUI toolkit experience will note that this same design is often seen under the name of "broadcaster-listener" (e.g., in Metrowerks' PowerPlant framework for the Macintosh). It works in much the same way: one sets up <literal>broadcasters</literal>, and then connects <literal>listeners</literal> to them; the broadcaster keeps a list of the objects listening to it, and when someone gives the broadcaster a message, it calls all of its objects in its list with the message. In <application>gtkmm</application>, signal objects play the role of broadcasters, and slots play the role of listeners - sort of. More on this later.)(In addition, you'd have the files <literal>ja.po</literal> and <literal>de.po</literal> in your <literal>po</literal> directory which contain the German and Japanese translations, respectively.)./docextract_to_xml.py -s ~/checkout/gnome/gtk+/gtk/ &gt; gtk_docs.xml
// creates its own adjustments
Gtk::TextView textview;
// uses the newly-created adjustment for the scrollbar as well
Gtk::Scrollbar vscrollbar (textview.get_vadjustment(), Gtk::ORIENTATION_VERTICAL);// note to translators: don't translate the "[noun]" part - it is
// just here to distinguish the string from another "jumps" string
text = strip(gettext("jumps[noun]"), "[noun]");//compiler error - no conversion from ustring to int.
int number = row[m_Columns.m_col_text];2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010<application>Gtk::Builder</application> checks for a null pointer, and checks that the widget is of the expected type, and will show warnings on the command line about these.<application>glibmm</application> provides the normal set of thread launching functions, mutexes, condition variables and scoped locking classes required for writing multi-threaded programs using C++.<application>gtkmm</application> 3 added some new classes:<application>gtkmm</application> 3 also made several small changes to the API, which you will probably encounter when porting code that used <application>gtkmm</application>-2.4. Here is a short list:<application>gtkmm</application> 3's library is called <literal>libgtkmm-3.0</literal> rather than <literal>libgtkmm-2.4</literal> and installs its headers in a similarly-versioned directory, so your pkg-config check should ask for <literal>gtkmm-3.0</literal> rather than <literal>gtkmm-2.4</literal>.<application>gtkmm</application> allows the programmer to control the lifetime (that is, the construction and destruction) of any widget in the same manner as any other C++ object. This flexibility allows you to use <literal>new</literal> and <literal>delete</literal> to create and destroy objects dynamically or to use regular class members (that are destroyed automatically when the class is destroyed) or to use local instances (that are destroyed when the instance goes out of scope). This flexibility is not present in some C++ GUI toolkits, which restrict the programmer to only a subset of C++'s memory management features.<application>gtkmm</application> allows you to write code using normal C++ techniques such as encapsulation, derivation, and polymorphism. As a C++ programmer you probably already realise that this leads to clearer and better organized code.<application>gtkmm</application> and Win32<application>gtkmm</application> applications can easily support multiple languages, including non-European languages such as Chinese and right-to-left languages such as Arabic. An appropriately-written and translated <application>gtkmm</application> application will use the appropriate language at runtime based on the user's environment.<application>gtkmm</application> applications consist of windows containing widgets, such as buttons and text boxes. In some other systems, widgets are called "controls". For each widget in your application's windows, there is a C++ object in your application's code. So you just need to call a method of the widget's class to affect the visible widget.<application>gtkmm</application> arranges widgets hierarchically, using <emphasis>containers</emphasis>. A Container widget contains other widgets. Most <application>gtkmm</application> widgets are containers. Windows, Notebook tabs, and Buttons are all container widgets. There are two flavours of containers: single-child containers, which are all descendants of <classname>Gtk::Bin</classname>, and multiple-child containers, which are descendants of <classname>Gtk::Container</classname>. Most widgets in <application>gtkmm</application> are descendants of <classname>Gtk::Bin</classname>, including <classname>Gtk::Window</classname>.<application>gtkmm</application> classes are designed with overriding in mind; they contain virtual member methods specifically intended to be overridden.<application>gtkmm</application> compared to Qt<application>gtkmm</application> currently works with the <ulink url="http://mingw.org/">MingW/GCC3.4 compiler</ulink> and Microsoft Visual C++ 2005 or later (including the freely available express editions) on the Windows platform. There is an <ulink url="ftp://ftp.gnome.org/pub/GNOME/binaries/win32/gtkmm"> installer</ulink> available for gtkmm on Microsoft Windows. Refer to <ulink url="http://live.gnome.org/gtkmm/MSWindows/"> http://live.gnome.org/gtkmm/MSWindows</ulink> for instructions how to use it.<application>gtkmm</application> has various widgets that can be visually adjusted using the mouse or the keyboard, such as the <classname>Range</classname> widgets (described in the <link linkend="chapter-range-widgets">Range Widgets</link> section). There are also a few widgets that display some adjustable part of a larger area, such as the <classname>Viewport</classname> widget. These widgets have <classname>Gtk::Adjustment</classname> objects that express this common part of their API.<application>gtkmm</application> involves less code compared to GTK+, which uses prefixed function names and lots of cast macros.<application>gtkmm</application> is a C++ wrapper for <ulink url="http://www.gtk.org/">GTK+</ulink>, a library used to create graphical user interfaces. It is licensed using the LGPL license, so you can develop open software, free software, or even commercial non-free software using <application>gtkmm</application> without purchasing licenses.<application>gtkmm</application> is a wrapper<application>gtkmm</application> is more type-safe, so the compiler can detect errors that would only be detected at run time when using C. This use of specific types also makes the API clearer because you can see what types should be used just by looking at a method's declaration.<application>gtkmm</application> is not a native C++ toolkit, but a C++ wrapper of a C toolkit. This separation of interface and implementation has advantages. The <application>gtkmm</application> developers spend most of their time talking about how <application>gtkmm</application> can present the clearest API, without awkward compromises due to obscure technical details. We contribute a little to the underlying GTK+ code base, but so do the C coders, and the Perl coders and the Python coders, etc. Therefore GTK+ benefits from a broader user base than language-specific toolkits - there are more implementers, more developers, more testers, and more users.<application>gtkmm</application> makes it very easy to derive new widgets by inheriting from an existing widget class, either by deriving from a container and adding child widgets, or by deriving from a single-item widget, and changing its behaviour. But you might occasionally find that no suitable starting point already exists. In this case, you can implement a widget from scratch.<application>gtkmm</application> provides an easy way to manage recently used documents. The classes involved in implementing this functionality are <classname>RecentManager</classname>, <classname>RecentChooserDialog</classname>, <classname>RecentChooserMenu</classname>, <classname>RecentChooserWidget</classname>, <classname>RecentAction</classname>, and <classname>RecentFilter</classname>.<application>gtkmm</application> provides four basic types of buttons:<application>gtkmm</application> provides the <function>manage()</function> function and <methodname>add()</methodname> methods to create and destroy widgets. Every widget except a top-level window must be added or packed into a container in order to be displayed. The <function>manage()</function> function marks a widget so that when the widget is added to a container, the container becomes responsible for deleting the widget.<application>gtkmm</application> signal handlers are strongly-typed, whereas <application>GTK+</application> C code allows you to connect a callback with the wrong number and type of arguments, leading to a segfault at runtime. And, unlike <application>Qt</application>, <application>gtkmm</application> achieves this without modifying the C++ language.<application>gtkmm</application> uses the <command>gmmproc</command> tool to generate most of its source code, using .defs files that define the APIs of <classname>GObject</classname>-based libraries. So it's quite easy to create additional gtkmm-style wrappers of other glib/GObject-based libraries.<application>gtkmm</application> uses the libsigc++ library to implement signals. Here is an example line of code that connects a Gtk::Button's "clicked" signal with a signal handler called "on_button_clicked": <placeholder-1/><application>gtkmm</application> was originally named gtk-- because GTK+ already has a + in the name. However, as -- is not easily indexed by search engines the package generally went by the name <application>gtkmm</application>, and that's what we stuck with.<application>gtkmm</application> widget classes have signal accessor methods, such as <methodname>Gtk::Button::signal_clicked()</methodname>, which allow you to connect your signal handler. Thanks to the flexibility of <application>libsigc++</application>, the callback library used by <application>gtkmm</application>, the signal handler can be almost any kind of function, but you will probably want to use a class method. Among <application>GTK+</application> C coders, these signal handlers are often named callbacks.<application>gtkmm</application>, like most GUI toolkits, is <emphasis>event-driven</emphasis>. When an event occurs, such as the press of a mouse button, the appropriate signal will be <emphasis>emitted</emphasis> by the Widget that was pressed. Each Widget has a different set of signals that it can emit. To make a button click result in an action, we set up a <emphasis>signal handler</emphasis> to catch the button's "clicked" signal.<application>gtkmm</application>-3.0 is a new version of the <application>gtkmm</application> API that installs in parallel with the older <application>gtkmm</application>-2.4 API. The last version of the <application>gtkmm</application>-2.4 API was <application>gtkmm</application> 2.24. <application>gtkmm</application> 3 has no major fundamental differences to <application>gtkmm</application> 2 but does make several small changes that were not possible while maintaining binary compatibility. If you never used the <application>gtkmm</application>-2.4 API then you can safely ignore this chapter.<application>intltool</application> / <application>xgettext</application> script extracts the strings and puts them in a <filename>mypackage.pot</filename> file. The translators of your application create their translations by first copying this <filename>.pot</filename> file to a <filename>localename.po</filename> file. A locale identifies a language and an encoding for that language, including date and numerical formats. Later, when the text in your source code has changed, the <literal>msmerge</literal> script is used to update the <filename>localename.po</filename> files from the regenerated <filename>.pot</filename> file.<classname>ButtonBox</classname>es help to make applications appear consistent because they use standard settings, such as inter-button spacing and packing.<classname>Gdk::Drawable</classname> was removed, with its methods moving into <classname>Gdk::Window</classname>.<classname>Gdk::Pixmap</classname> and <classname>Gdk::Bitmap</classname> were removed in favour of <classname>Gdk::Pixbuf</classname>.<classname>Gdk::RGBA</classname> replaces <classname>Color</classname>, adding an alpha component for opacity. <classname>Colormap</classname> was removed, along with its awkward use to allocate colors.<classname>Glib::ListHandle&lt;Gtk::Widget*&gt;</classname>: Use <classname>std::vector&lt;Gtk::Widget*&gt;</classname>, <classname>std::list&lt;Gtk::Widget*&gt;</classname>, etc.<classname>Glib::SListHandle&lt;Gtk::Widget*&gt;</classname>: Use <classname>std::vector&lt;Gtk::Widget*&gt;</classname>, <classname>std::list&lt;Gtk::Widget*&gt;</classname>, etc.<classname>Glib::StringArrayHandle</classname> or <classname>Glib::ArrayHandle&lt;Glib::ustring&gt;</classname>: Use <classname>std::vector&lt;Glib::ustring&gt;</classname>, <classname>std::list&lt;Glib::ustring&gt;</classname>, <type>const char*[]</type>, etc.<classname>Gtk::Adjustment</classname> and <classname>IconSet</classname> and <classname>Gdk::Cursor</classname> are now used via <classname>Glib::RefPtr</classname>.<classname>Gtk::AppChooser</classname>, <classname>Gtk::AppChooserButton</classname>, <classname>Gtk::AppChooserDialog</classname> allow the user to select an installed application to open a particular type of content.<classname>Gtk::Box</classname> arranges its child widgets vertically or horizontally. Use <methodname>pack_start()</methodname> and <methodname>pack_end()</methodname> to insert child widgets.<classname>Gtk::Box</classname>, <classname>Gtk::ButtonBox</classname>, <classname>Gtk::IconView</classname>, <classname>Gtk::Paned</classname>, <classname>Gtk::ProgressBar</classname>, <classname>Gtk::ScaleButton</classname>, <classname>Gtk::Scrollbar</classname> and <classname>Gtk::Separator</classname> now derive from <classname>Gtk::Orientable</classname>, allowing their orientation (vertical or horizontal) to be specified without requiring the use of a derived class such as <classname>Gtk::HBox</classname>.<classname>Gtk::Builder</classname> must be used via a <classname>Glib::RefPtr</classname>. Like all such classes, you need to use a <methodname>create()</methodname> method to instantiate it. For instance, <placeholder-1/> This will instantiate the windows defined in the .glade file, though they will not be shown immediately unless you have specified that via the <guilabel>Properties</guilabel> window in <application>Glade</application>.<classname>Gtk::Button</classname> is also a container so you could put any other widget, such as a <classname>Gtk::Image</classname> into it.<classname>Gtk::CellLayout</classname>, used by <classname>Gtk::IconView</classname>, <classname>Gtk::TreeView::Column</classname> and <classname>Gtk::ComboBox</classname>, now has a <classname>Gtk::CellArea</classname> which can be used to specify more details of how the <classname>CellRenderer</classname>s are arranged and aligned.<classname>Gtk::CheckButton</classname> inherits from <classname>Gtk::ToggleButton</classname>. The only real difference between the two is <classname>Gtk::CheckButton</classname>'s appearance. You can check, set, and toggle a checkbox using the same member methods as for <classname>Gtk::ToggleButton</classname>.<classname>Gtk::Grid</classname> arranges its child widgets in rows and columns. Use <methodname>attach()</methodname>, <methodname>attach_next_to()</methodname> and <methodname>add()</methodname> to insert child widgets.<classname>Gtk::Grid</classname> is a new container widget that will eventually replace <classname>Gtk::Box</classname> and <classname>Gtk::Table</classname>. It arranges its children according to properties of those children rather than its own layout details.<classname>Gtk::IconView</classname>, <classname>Gtk::TextView</classname>, <classname>Gtk::TreeView</classname> and other widgets derive from Scrollable instead of having their own methods such as <methodname>get_vadjustment()</methodname> and instead of having their own set_scroll_adjustments signal.<classname>Gtk::Scale</classname> and <classname>Gtk::Scrollbar</classname> both inherit from <classname>Gtk::Range</classname> and share much functionality. They contain a "trough" and a "slider" (sometimes called a "thumbwheel" in other GUI environments). Dragging the slider with the pointer moves it within the trough, while clicking in the trough advances the slider towards the location of the click, either completely, or by a designated amount, depending on which mouse button is used. This should be familiar scrollbar behaviour.<classname>Gtk::Scale</classname> widgets (or "sliders") allow the user to visually select and manipulate a value within a specific range. You might use one, for instance, to adjust the magnification level on a zoomed preview of a picture, or to control the brightness of a colour, or to specify the number of minutes of inactivity before a screensaver takes over the screen.<classname>Gtk::Style</classname> and <classname>Gtk::Rc</classname> were removed, replaced by <classname>Gtk::StyleContext</classname>, and <classname>Gtk::StyleProvider</classname>s, such as <classname>Gtk::CssProvider</classname>.<classname>Gtk::Switch</classname> displays On/Off states more explictly than <classname>Gtk::CheckBox</classname>. It may be useful, for instance, when allowing users to activate hardware.<classname>Gtk::Table</classname> allows us to place widgets in a grid, similar to <classname>Gtk::Grid</classname>.<classname>Gtk::Table</classname> is deprecated from <application>gtkmm</application> version 3.4 and should not be used in newly-written code. Use <classname>Gtk::Grid</classname> instead.<classname>Gtk::TargetEntry</classname> objects contain this information: <placeholder-1/><classname>Gtk::TextBuffer</classname> is a model containing the data for the <classname>Gtk::TextView</classname>, like the <classname>Gtk::TreeModel</classname> used by <classname>Gtk::TreeView</classname>. This allows two or more <classname>Gtk::TextView</classname>s to share the same <classname>TextBuffer</classname>, and allows those TextBuffers to be displayed slightly differently. Or you could maintain several <classname>Gtk::TextBuffer</classname>s and choose to display each one at different times in the same <classname>Gtk::TextView</classname> widget.<classname>Gtk::TextView</classname> has various <methodname>scroll_to_*()</methodname> methods. These allow you to ensure that a particular part of the text buffer is visible. For instance, your application's Find feature might use <methodname>Gtk::TextView::scroll_to_iter()</methodname> to show the found text.<classname>Gtk::ToggleButton</classname> is most useful as a base class for the <classname>Gtk::CheckButton</classname> and <classname>Gtk::RadioButton</classname> classes.<classname>Gtk::ToolItem</classname>s can then be added to the group. For instance, like so:<classname>Gtk::TreeModel</classname> provides a C++ Standard Library-style container of its children, via the <methodname>children()</methodname> method. You can use the familiar <methodname>begin()</methodname> and <methodname>end()</methodname> methods iterator incrementing, like so:<classname>Gtk::TreeStore</classname> models can have child items. Add them with the <methodname>append()</methodname>, <methodname>prepend()</methodname>, or <methodname>insert()</methodname> methods, like so:<classname>Gtk::TreeView</classname> already implements simple drag-and-drop when used with the <classname>Gtk::ListStore</classname> or <classname>Gtk::TreeStore</classname> models. If necessary, it also allows you to implement more complex behaviour when items are dragged and dropped, using the normal <link linkend="chapter-draganddrop">Drag and Drop</link> API.<classname>Gtk::Widget</classname> has several methods and signals which are prefixed with "drag_". These are used for Drag and Drop.<classname>Menus</classname> are normally just added to a window, but they can also be displayed temporarily as the result of a mouse button click. For instance, a context menu might be displayed when the user clicks their right mouse button.<classname>MessageDialog</classname> is a convenience class, used to create simple, standard message dialogs, with a message, an icon, and buttons for user response. You can specify the type of message and the text in the constructor, as well as specifying standard buttons via the <literal>Gtk::ButtonsType</literal> enum.<classname>RadioButtons</classname> are "off" when created; this means that when you first make a group of them, they will all be off. Don't forget to turn one of them on using <methodname>set_active()</methodname>:<classname>Range</classname> widgets typically connect a handler to this signal, which changes their appearance to reflect the change - for example, the size of the slider in a scrollbar will grow or shrink in inverse proportion to the difference between the <parameter>lower</parameter> and <parameter>upper</parameter> values of its <classname>Adjustment</classname>.<classname>RecentChooser</classname> is an interface that can be implemented by widgets displaying the list of recently used files. <application>gtkmm</application> provides four built-in implementations for choosing recent files: <classname>RecentChooserWidget</classname>, <classname>RecentChooserDialog</classname>, <classname>RecentChooserMenu</classname>, and <classname>RecentAction</classname>.<classname>RecentChooserMenu</classname> and <classname>RecentAction</classname> allow you to list recently used files as a menu.<classname>RecentChooserWidget</classname> is a simple widget for displaying a list of recently used files. <classname>RecentChooserWidget</classname> is the basic building block for <classname>RecentChooserDialog</classname>, but you can embed it into your user interface if you want to.<classname>RecentManager</classname> acts as a database of recently used files. You use this class to register new files, remove files from the list, or look up recently used files. There is one list of recently used files per user.<classname>RecentManager</classname> is the model of a model-view pattern, where the view is a class that implements the <classname>RecentChooser</classname> interface.<classname>Scale</classname> widgets can display their current value as a number next to the trough. By default they show the value, but you can change this with the <methodname>set_draw_value()</methodname> method.<classname>ScrolledWindow</classname> widgets create a scrollable area. You can insert any type of widget into a <classname>ScrolledWindow</classname> window, and it will be accessible regardless of its size by using the scrollbars. Note that <classname>ScrolledWindow</classname> is not a <classname>Gtk::Window</classname> despite the slightly misleading name.<classname>SpinButton</classname>s use an <link linkend="chapter-adjustment">Adjustment</link> object to hold information about the range of values. These Adjustment attributes are used by the Spin Button like so: <placeholder-1/><classname>TextBuffer</classname> iterators are generally invalidated when the text changes, but you can use a <classname>Gtk::TextBuffer::Mark</classname> to remember a position in these situations. For instance,<classname>TextView</classname> has various methods which allow you to change the presentation of the buffer for this particular view. Some of these may be overridden by the <classname>Gtk::TextTag</classname>s in the buffer, if they specify the same things. For instance, <methodname>set_left_margin()</methodname>, <methodname>set_right_margin()</methodname>, <methodname>set_indent()</methodname>, etc.<classname>ToggleButton</classname>s are like normal <classname>Button</classname>s, but when clicked they remain activated, or pressed, until clicked again.<classname>Widget</classname>s can be identified as sources or destinations using these <classname>Gtk::Widget</classname> methods:<command>gmmproc</command> will warn you on stdout about functions and signals that you have forgotten to wrap, helping to ensure that you are wrapping the complete API. But if you don't want to wrap some functions or signals, or if you chose to hand-code some methods then you can use the _IGNORE() or _IGNORE_SIGNAL() macro to make <command>gmmproc</command> stop complaining.<filename>libsomething</filename>: Contains the main include file and the pkg-config .pc file.<filename>libsomethingmm</filename>: Contains generated and hand-written .h and .cc files.<filename>libsomethingmm</filename>: The top-level directory.<filename>private</filename>: Contains generated <filename>*_p.h</filename> files.<filename>src</filename>: Contains .hg and .ccg source files.<function>_WRAP_METHOD()</function> also supports setting C++ output parameters from C output parameters if the C function being wrapped has any. Suppose, for example, that we want to wrap the following C function that returns a value in its C output parameter <parameter>rect</parameter>: <placeholder-1/> To have <command>gmmproc</command> place the value returned in the C++ <parameter>rect</parameter> output parameter, something like the following <function>_WRAP_METHOD()</function> directive could be used: <placeholder-2/> The <literal>{&gt;&gt;}</literal> following the <parameter>rect</parameter> parameter name indicates that the C++ output parameter should be set from the value returned in the C parameter from the C function. <command>gmmproc</command> will generate a declaration of a temporary variable in which to store the value of the C output parameter and a statement that sets the C++ output parameter from the temporary variable. In this case it may be necessary to have an <function>_INITIALIZATION()</function> describing how to set a <classname>Gdk::Rectangle&amp;</classname> from a <classname>GdkRectangle*</classname> such as the following: <placeholder-3/><function>_WRAP_METHOD()</function>, <function>_WRAP_SIGNAL()</function>, and <function>_WRAP_PROPERTY()</function><function>sigc::bind()</function> is not commonly used, but you might find it helpful sometimes. If you are familiar with <application>GTK+</application> programming then you have probably noticed that this is similar to the extra <literal>gpointer data</literal> arguments which all GTK+ callbacks have. This is generally overused in <application>GTK+</application> to pass information that should be stored as member data in a derived widget, but widget derivation is very difficult in C. We have far less need of this hack in <application>gtkmm</application>.<function>sigc::ptr_fun()</function> generates a <classname>sigc::slot</classname>. A slot is an object which looks and feels like a function, but is actually an object. These are also known as function objects, or functors. <function>sigc::ptr_fun()</function> generates a slot for a standalone function or static method. <function>sigc::mem_fun()</function> generates a slot for a member method of a particular instance.<literal>$3</literal> will be replaced by the output parameter name of the C++ method and <literal>$4</literal> will be replaced by the return of the C function when this initialization is used by gmmproc. For convenience, <literal>$1</literal> will also be replaced by the C++ type without the ampersand (&amp;) and <literal>$2</literal> will be replaced by the C type.<literal>$3</literal> will be replaced by the parameter name when this conversion is used by gmmproc.<literal>Gtk::PACK_EXPAND_PADDING</literal>: Extra space is filled with padding. The widgets will be spaced out evenly, but their sizes won't change - there will be empty space between the widgets instead.<literal>Gtk::PACK_EXPAND_WIDGET</literal>: Extra space is taken up by increasing the child widget size, without changing the amount of space between widgets.<literal>Gtk::PACK_SHRINK</literal>: Space is contracted to the child widget size. The widget will take up just-enough space and never expand.<literal>Gtk::UPDATE_CONTINUOUS</literal> - This is the default. The <literal>value_changed</literal> signal is emitted continuously, i.e. whenever the slider is moved by even the tiniest amount.<literal>Gtk::UPDATE_DELAYED</literal> - The <literal>value_changed</literal> signal is emitted when the user releases the mouse button, or if the slider stops moving for a short period of time.<literal>Gtk::UPDATE_DISCONTINUOUS</literal> - The <literal>value_changed</literal> signal is only emitted once the slider has stopped moving and the user has released the mouse button.<literal>LINGUAS</literal> contains an alphabetically sorted list of codes identifying the languages for which your program is translated (comment lines starting with a <literal>#</literal> are ignored). Each language code listed in the <literal>LINGUAS</literal> file must have a corresponding <literal>.po</literal> file. So, if your program has German and Japanese translations, your <literal>LINGUAS</literal> file would look like this:<literal>POTFILES.in</literal> is a list of paths to all files which contain strings marked up for translation, starting from the project root directory. So for example, if your project sources were located in a subdirectory named <literal>src</literal>, and you had two files that contained strings that should be translated, your <literal>POTFILES.in</literal> file might look like this:<literal>actions</literal> indicates the Drag and Drop actions which this destination can receive - see the description above.<literal>actions</literal> is an ORed combination of values, which specified which Drag and Drop operations will be possible from this source - for instance, copy, move, or link. The user can choose between the actions by using modifier keys, such as <keycap>Shift</keycap> to change from <literal>copy</literal> to <literal>move</literal>, and this will be shown by a different cursor.<literal>begin_print</literal>: You must handle this signal, because this is where you create and set up a <classname>Pango::Layout</classname> using the provided <classname>Gtk::PrintContext</classname>, and break up your printing output into pages.<literal>done</literal>: This signal is emitted when printing is finished, meaning when the print data is spooled. Note that the provided <literal>Gtk::PrintOperationResult</literal> may indicate that an error occurred. In any case you probably want to notify the user about the final status.<literal>drag_begin</literal>: Provides DragContext.<literal>drag_data_delete</literal>: Gives the source the opportunity to delete the original data if that's appropriate.<literal>drag_data_get</literal>: Provides <literal>info</literal> about the dragged data format, and a <literal>Gtk::SelectionData</literal> structure, in which you should put the requested data.<literal>drag_data_received</literal>: Provides <literal>info</literal> about the dragged data format, and a <literal>Gtk::SelectionData</literal> structure which contains the dropped data. You should call the <methodname>drag_finish()</methodname> method of the <literal>DragContext</literal> to indicate whether the operation was successful.<literal>drag_drop</literal>: Provides DragContext and coordinates.<literal>drag_end</literal>: Provides DragContext.<literal>drag_motion</literal>: Provides DragContext and coordinates. You can call the drag_status() method of the DragContext to indicate which target will be accepted.<literal>draw_page</literal>: You must handle this signal, which provides a <classname>PrintContext</classname> and a page number. The <classname>PrintContext</classname> should be used to create a <classname>Cairo::Context</classname> into which the provided page should be drawn. To render text, iterate over the <classname>Pango::Layout</classname> you created in the <literal>begin_print</literal> handler.<literal>end_print</literal>: A handler for it is a safe place to free any resources related to a <classname>PrintOperation</classname>. If you have your custom class that inherits from <classname>PrintOperation</classname>, it is naturally simpler to do it in the destructor.<literal>flags</literal> is an ORed combination of values which indicates how the widget will respond visually to Drag and Drop items.<literal>lower</literal>: lower range value<literal>page_increment</literal>: value to increment/decrement when pressing mouse button 2 on a button<literal>page_size</literal>: unused<literal>paginate</literal>: Pagination is potentially slow so if you need to monitor it you can call the <methodname>PrintOperation::set_show_progress()</methodname> method and handle this signal.<literal>request_page_setup</literal>: Provides a <classname>PrintContext</classname>, page number and <classname>Gtk::PageSetup</classname>. Handle this signal if you need to modify page setup on a per-page basis.<literal>start_button_mask</literal> is an ORed combination of values, which specify which modifier key or mouse button must be pressed to start the drag.<literal>status_changed</literal>: Emitted whenever a print job's status changes, until it is finished. Call the <methodname>PrintOperation::set_track_print_status()</methodname> method to monitor the job status after spooling. To see the status, use <methodname>get_status()</methodname> or <methodname>get_status_string()</methodname>.<literal>step_increment</literal>: value to increment/decrement when pressing mouse button 1 on a button<literal>upper</literal>: upper range value<literal>value</literal>: value for the Spin Button<methodname>Gtk::Widget::show()</methodname> lets <application>gtkmm</application> know that we have finished setting the attributes of the widget, and that it is ready to be displayed. You can use <methodname>Gtk::Widget::hide()</methodname> to make it disappear again. The order in which you show the widgets is not important, but we do suggest that you show the top-level window last; this way, the whole window will appear with its contents already drawn. Otherwise, the user will first see a blank window, into which the widgets will be gradually drawn.<methodname>child_type_vfunc()</methodname>: Return what type of child can be added.<methodname>forall_vfunc()</methodname>: Call the same callback for each of the children.<methodname>get_preferred_height_for_width_vfunc()</methodname>: Calculate the minimum and natural height of the container, if it would be given the specified width.<methodname>get_preferred_height_for_width_vfunc()</methodname>: Calculate the minimum and natural height of the widget, if it would be given the specified width.<methodname>get_preferred_height_vfunc()</methodname>: Calculate the minimum and natural height of the container.<methodname>get_preferred_height_vfunc()</methodname>: Calculate the minimum and natural height of the widget.<methodname>get_preferred_width_for_height_vfunc()</methodname>: Calculate the minimum and natural width of the container, if it would be given the specified height.<methodname>get_preferred_width_for_height_vfunc()</methodname>: Calculate the minimum and natural width of the widget, if it would be given the specified height.<methodname>get_preferred_width_vfunc()</methodname>: Calculate the minimum and natural width of the container.<methodname>get_preferred_width_vfunc()</methodname>: Calculate the minimum and natural width of the widget.<methodname>get_request_mode_vfunc()</methodname>: (optional) Return what <literal>Gtk::SizeRequestMode</literal> is preferred by the widget.<methodname>get_request_mode_vfunc()</methodname>: Return what <literal>Gtk::SizeRequestMode</literal> is preferred by the container.<methodname>get_widget()</methodname> returns child widgets that are <function>manage()</function>ed (see the <link linkend="chapter-memory">Memory Management</link> chapter), so they will be deleted when their parent container is deleted. So, if you get only a child widget from <application>Gtk::Builder</application>, instead of a whole window, then you must either put it in a <classname>Container</classname> or delete it. <classname>Windows</classname> (such as <classname>Dialogs</classname>) cannot be managed because they have no parent container, so you must delete them at some point.<methodname>on_add()</methodname>: Add a child widget to the container.<methodname>on_draw()</methodname>: Draw on the supplied <classname>Cairo::Context</classname>.<methodname>on_map()</methodname>: (optional)<methodname>on_realize()</methodname>: Associate a <classname>Gdk::Window</classname> with the widget.<methodname>on_remove()</methodname>: Remove a child widget from the container.<methodname>on_size_allocate()</methodname> receives the actual height and width that the parent container has decided to give to your widget. This might be more than the minimum, or even more than the natural size, for instance if the top-level window has been expanded. You might choose to ignore the extra space and leave a blank area, or you might choose to expand your child widgets to fill the space, or you might choose to expand the padding between your widgets. It's your container, so you decide. Don't forget to call <methodname>set_allocation()</methodname> inside your <methodname>on_size_allocate()</methodname> implementation to actually use the allocated space that has been offered by the parent container.<methodname>on_size_allocate()</methodname>: Position the child widgets, given the height and width that the container has actually been given.<methodname>on_size_allocate()</methodname>: Position the widget, given the height and width that it has actually been given.<methodname>on_unmap()</methodname>: (optional)<methodname>on_unrealize()</methodname>: (optional) Break the association with the <classname>Gdk::Window</classname>.<methodname>run()</methodname> may return <literal>PRINT_OPERATION_RESULT_IN_PROGRESS</literal>. To track status and handle the result or error you need to implement signal handlers for the <literal>done</literal> and <literal>status_changed</literal> signals:<placeholder-1/> (or <placeholder-2/> for filenames)<placeholder-1/> Now, when objects of type <classname>MyContainer</classname> are destroyed, the button will also be deleted. It is no longer necessary to delete <varname>pButton</varname> to free the button's memory; its deletion has been delegated to the <classname>MyContainer</classname> object.<placeholder-1/> example package<type>GdkEventButton</type> is a structure containing the event's parameters, such as the coordinates of the mouse pointer at the time the button was pressed. There are several different types of <type>GdkEvent</type> structures for the various events.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Button.html"><classname>Gtk::Button</classname></ulink>. Standard buttons, usually marked with a label or picture. Pushing one triggers an action. See the <link linkend="sec-pushbuttons">Button</link> section.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1CheckButton.html"><classname>Gtk::CheckButton</classname></ulink>. These act like ToggleButtons, but show their state in small squares, with their label at the side. They should be used in most situations which require an on/off setting. See the <link linkend="sec-checkboxes">CheckButton</link> section.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1RadioButton.html"><classname>Gtk::RadioButton</classname></ulink>. Named after the station selectors on old car radios, these buttons are used in groups for options which are mutually exclusive. Pressing one causes all the others in its group to turn off. They are similar to CheckBoxes (a small widget with a label at the side), but usually look different. See the <link linkend="sec-radio-buttons">RadioButton</link> section.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToggleButton.html"><classname>Gtk::ToggleButton</classname></ulink>. Unlike a normal Button, which springs back up, a ToggleButton stays down until you press it again. It might be useful as an on/off switch. See the <link linkend="sec-toggle-buttons">ToggleButton</link> section.<varname>app_exec</varname>: The command line to be used to launch this resource. This string may contain the "f" and "u" escape characters which will be expanded to the resource file path and URI respectively<varname>app_name</varname>: The name of the application that registered the resource<varname>description</varname>: A short description of the resource as a UTF-8 encoded string<varname>display_name</varname>: The name of the resource to be used for display as a UTF-8 encoded string<varname>groups</varname>: A list of groups associated with this item. Groups are essentially arbitrary strings associated with a particular resource. They can be thought of as 'categories' (such as "email", "graphics", etc) or tags for the resource.<varname>is_private</varname>: Whether this resource should be visible only to applications that have registered it or not<varname>mime_type</varname>: The MIME type of the resourceA <classname>ComboBox</classname> may contain an <classname>Entry</classname> widget for entering of arbitrary text, by specifying <literal>true</literal> for the constructor's <literal>has_entry</literal> parameter.A <classname>Entry</classname> widget can offer a drop-down list of pre-existing choices based on the first few characters typed by the user. For instance, a search dialog could suggest text from previous searches.A <classname>Glib::Dispatcher</classname> is used for sending notifications from the worker thread to the GUI thread. The <classname>ExampleWorker</classname> class contains data which is accessed by both threads. This data is protected by a <classname>Glib::Threads::Mutex</classname>. Only the GUI thread updates the GUI.A <classname>Glib::Dispatcher</classname> object can be emitted on by the receiver thread as well as by a worker thread, although this should be done within reasonable bounds. On unix-like systems <classname>Glib::Dispatcher</classname> objects share a single common pipe, which could in theory at least fill up on a very heavily loaded system running a program with a very large number of <classname>Dispatcher</classname> objects in use. Were the pipe to fill up before the receiver thread's main loop has had an opportunity to read from it to empty it, and the receiver thread attempt to emit and so write to it when it is in that condition, the receiver thread would block on the write, so deadlocking. Where the receiver thread is to emit, a normal <classname>sigc::signal&lt;void&gt;</classname> object could of course be used instead.A <classname>Grid</classname> dynamically lays out child widgets in rows and columns. The dimensions of the grid do not need to be specified in the constructor.A <classname>Notebook</classname> has a set of stacked <literal>pages</literal>, each of which contains widgets. Labelled <literal>tabs</literal> allow the user to select the pages. <classname>Notebook</classname>s allow several sets of widgets to be placed in a small space, by only showing one page at a time. For instance, they are often used in preferences dialogs.A <classname>Plug</classname> is a special kind of Window that can be plugged into a <classname>Socket</classname>. Besides the normal properties and methods of <classname>Gtk::Window</classname>, a <classname>Plug</classname> provides a constructor that takes the ID of a <classname>Socket</classname>, which will automatically embed the <classname>Plug</classname> into the <classname>Socket</classname> that matches that ID.A <classname>ProgressBar</classname> is horizontal and left-to-right by default, but you can change it to a vertical progress bar by using the <methodname>set_orientation()</methodname> method.A <classname>RecentInfo</classname> object is essentially an object containing all of the metadata about a single recently-used file. You can use this object to look up any of the properties listed <link linkend="list-file-metadata">above</link>.A <classname>Socket</classname> is a special kind of container widget that provides the ability to embed widgets from one process into another process in a way that is transparent to the user.A <classname>ToolPalette</classname> is similar to a <classname>Toolbar</classname> but can contain a grid of items, categorized into groups. The user may hide or expand each group. As in a toolbar, the items may be displayed as only icons, as only text, or as icons with text.A <classname>sigc::signal</classname> object should be regarded as owned by the thread which created it. Only that thread should connect a <classname>sigc::slot</classname> object to the signal object, and only that thread should <methodname>emit()</methodname> or call <methodname>operator()()</methodname> on the signal, or null any connected <classname>sigc::slot</classname> object. It follows (amongst other things) that any signal object provided by a <application>gtkmm</application> widget should only be operated on in the main GUI thread and any object deriving from <classname>sigc::trackable</classname> having its non-static methods referenced by slots connected to the signal object should only be destroyed in that thread.A <classname>sigc::slot</classname> object created by a call to <function>sigc::mem_fun()</function> which references a method of a class deriving from <classname>sigc::trackable</classname> should never be copied to another thread, nor destroyed by a different thread than the one which created it. (One consequence of this is that <methodname>Glib::Threads::Thread::create()</methodname> should not be called with a slot argument created by a call to <function>sigc::mem_fun()</function> which represents a method of such a class. It is however safe to pass <methodname>Glib::Threads::Thread::create()</methodname> a function object representing such a method by using, say, <function>boost::bind()</function> or, in C++11, <function>std::bind()</function> or a C++11 lambda expression.)A child widget can be added to the <classname>EventBox</classname> using:A little example follows. To use the example just execute it from a terminal; it doesn't create a window. It will create a pipe named <literal>testfifo</literal> in the current directory. Then start another shell and execute <literal>echo "Hello" &gt; testfifo</literal>. The example will print each line you enter until you execute <literal>echo "Q" &gt; testfifo</literal>.A nifty feature of Glib (one of the libraries underlying <application>gtkmm</application>) is the ability to have it check for data on a file descriptor for you. This is especially useful for networking applications. The following method is used to do this:A properly internationalized application will not make assumptions about the number of bytes in a character. That means that you shouldn't use pointer arithmetic to step through the characters in a string, and it means you shouldn't use <classname>std::string</classname> or standard C functions such as <function>strlen()</function> because they make the same assumption.A rule to which there may be exceptions: If the virtual C function returns a pointer to an object derived from <classname>GObject</classname>, i.e. a reference-counted object, then the virtual C++ function shall return a <classname>Glib::RefPtr&lt;&gt;</classname> object. One of the extra arguments <parameter>refreturn</parameter> or <parameter>refreturn_ctype</parameter> is required.A smartpointer acts much like a normal pointer. Here are a few examples.A target can be in a variety of binary formats. This chapter, and the examples, assume that the data is 8-bit text. This would allow us to use an XML format for the clipboard data. However this would probably not be appropriate for binary data such as images. <classname>Gtk::Clipboard</classname> provides overloads that allow you to specify the format in more detail if necessary.AM_CPPFLAGSAM_CPPFLAGS = ... -DPROGRAMNAME_LOCALEDIR=\"${PROGRAMNAME_LOCALEDIR}\"AM_CXXFLAGSATKAboutDialogAccessing widgetsActionsActivity ModeAdd <literal>INTLTOOL_FILES</literal> to the <literal>EXTRA_DIST</literal> list of files. This ensures that when you do a <command>make dist</command>, these commands will be included in the source tarball.Add <literal>po</literal> to the <literal>SUBDIRS</literal> variable. Without this, your translations won't get built and installed when you build the programAdd a default constructor.Add methods to wrap parts of the C API.Add rows to the model with the <methodname>append()</methodname>, <methodname>prepend()</methodname>, or <methodname>insert()</methodname> methods.Adding Items to the List of Recent FilesAdding RowsAdding View ColumnsAdding child rowsAdding properties, and ensuring that they interact properly with each other, is relatively difficult to correct in the C library, but it is possible, so do file a bug and try to send a patch to the relevant maintainer.Adding widgetsAdditional command-line flags passed to the <filename>generate_wrap_init.pl</filename> script, such as the C++ namespace and the parent directory prefix of include files.Additionally, mouse button 3 can be used to jump directly to the <literal>upper</literal> or <literal>lower</literal> values.Adjustment InternalsAdjustmentsAfter a <classname>Socket</classname> or <classname>Plug</classname> object is realized, you can obtain its ID with its <methodname>get_id()</methodname> function. This ID can then be shared with other processes so that other processes know how to connect to each other.After appending rows to this model, you should provide the model to the <classname>ComboBox</classname> with the <methodname>set_model()</methodname> method. Then use the <methodname>pack_start()</methodname> or <methodname>pack_end()</methodname> methods to specify what columns will be displayed in the ComboBox. As with the TreeView you may either use the default cell renderer by passing the <classname>TreeModelColumn</classname> to the pack methods, or you may instantiate a specific <classname>CellRenderer</classname> and specify a particular mapping with either <methodname>add_attribute()</methodname> or <methodname>set_cell_data_func()</methodname>. Note that these methods are in the <classname>CellLayout</classname> base class.After building and running this program, try resizing the window to see the behaviour. Also, try playing with the options to <methodname>pack_start()</methodname> while reading the <link linkend="sec-boxes">Boxes</link> section.After drawing the outline, we go around the clock and draw ticks for every hour, with a larger tick at 12, 3, 6, and 9. Now we're finally ready to implement the time-keeping functionality of the clock, which simply involves getting the current values for hours, minutes and seconds, and drawing the hands at the correct angles.After putting the source code in <literal>simple.cc</literal> you can compile the above program with <application>gcc</application> using: <placeholder-1/> Note that you must surround the <literal>pkg-config</literal> invocation with backquotes. Backquotes cause the shell to execute the command inside them, and to use the command's output as part of the command line. Note also that <literal>simple.cc</literal> must come before the <literal>pkg-config</literal> invocation on the command line.After selecting the <guimenuitem>Recent Files Dialog</guimenuitem> menu item, you should see something similar to the following window.After setting the correct moduleset, you need to tell <application>jhbuild</application> which module or modules to build. To build <application>gtkmm</application> and all of its dependencies, set <varname>modules</varname> like so: <placeholder-1/>After starting <filename>socket</filename>, you should see the following output in the terminal:After which you should see something like the following:After you've created and set up the filter to match only the items you want, you can apply a filter to a chooser widget with the <methodname>RecentChooser::add_filter()</methodname> function.After you've finished creating your path, you still haven't drawn anything visible yet. To make the path visible, you must use the function <methodname>stroke()</methodname> which will stroke the current path with the line width and style specified in your <classname>Cairo::Context</classname> object. After stroking, the current path will be cleared so that you can start on your next path.After you've installed all of the dependencies, download the <application>gtkmm</application> source code, unpack it, and change to the newly created directory. <application>gtkmm</application> can be built and installed with the following sequence of commands:After you've installed the git version of <application>gtkmm</application>, you're ready to start using and experimenting with it. In order to use the new version of <application>gtkmm</application> you've just installed, you need to set some environment variables so that your <filename>configure</filename> script knows where to find the new libraries. Fortunately, <application>jhbuild</application> offers an easy solution to this problem. Executing the command <command>jhbuild shell</command> will start a new shell with all of the correct environment variables set. Now if you re-configure and build your project just as you usually do, it should link against the newly installed libraries. To return to your previous environment, simply exit the <application>jhbuild</application> shell.AhlstedtAlignmentAll <application>gtkmm</application> programs must include certain <application>gtkmm</application> headers; <literal>gtkmm.h</literal> includes the entire <application>gtkmm</application> kit. This is usually not a good idea, because it includes a megabyte or so of headers, but for simple programs, it suffices.All container widgets derive from <classname>Gtk::Container</classname>, not always directly. Some container widgets, such as <classname>Gtk::Grid</classname> can hold many child widgets, so these typically have more complex interfaces. Others, such as <classname>Gtk::Frame</classname> contain only one child widget.All deprecated API was removed in <application>gtkmm</application> 3.0, though there will be new deprecations in future versions.All mentions of <varname>skeleton</varname> should be replaced by the correct name of the C library you are wrapping, such as "something" or "libsomething". In the same manner, all instances of <varname>SKELETON</varname> should be replaced by "SOMETHING" or "LIBSOMETHING", and all occurrences of <varname>Skeleton</varname> changed to "Something".Also, the value can be drawn in different positions relative to the trough, specified by the <methodname>set_value_pos()</methodname> method.Alternatively, if a complete list of possible entries would be too large or too inconvenient to generate, a callback slot may instead be specified with <methodname>set_match_func()</methodname>. This is also useful if you wish to match on a part of the string other than the start.Alternatively, you can let a widget's container control when the widget is destroyed. In most cases, you want a widget to last only as long as the container it is in. To delegate the management of a widget's lifetime to its container, first create it with <function>Gtk::manage()</function> and pack it into its container with <methodname>Gtk::Container::add()</methodname>, <methodname>Gtk::Box::pack_start()</methodname>, or a similar method. Now the widget will be destroyed whenever its container is destroyed.Although <application>glib</application> is itself thread-safe, any <application>glibmm</application> wrappers which use <application>libsigc++</application> will not be. So for example, only the thread in which a main loop runs should call <methodname>Glib::SignalIdle::connect()</methodname>, <methodname>Glib::SignalIO::connect()</methodname>, <methodname>Glib::SignalTimeout::connect()</methodname>, <methodname>Glib::SignalTimeout::connect_seconds</methodname> for that main loop, or manipulate any <classname>sigc::connection</classname> object returned by them.Although <application>gtkmm</application> widget instances have lifetimes and scopes just like those of other C++ classes, <application>gtkmm</application> has an optional time-saving feature that you will see in some of the examples. <function>Gtk::manage()</function> allows you to say that a child widget is owned by the container into which you place it. This allows you to <function>new</function> the widget, add it to the container and forget about deleting it. You can learn more about <application>gtkmm</application> memory management techniques in the <link linkend="chapter-memory">Memory Management chapter</link>.Although Cairo can render text, it's not meant to be a replacement for Pango. Pango is a better choice if you need to perform more advanced text rendering such as wrapping or ellipsizing text. Drawing text with Cairo should only be done if the text is part of a graphic.Although the <literal>custom_widget_apply</literal> signal provides the widget you previously created, to simplify things you can keep the widgets you expect to contain some user input as class members. For example, let's say you have a <classname>Gtk::Entry</classname> called <literal>m_Entry</literal> as a member of your <classname>CustomPrintOperation</classname> class: <placeholder-1/>Although the name <classname>EventBox</classname> emphasises the event-handling method, the widget can also be used for clipping (and more; see the example below).Although you can specify the layout and appearance of windows and widgets with C++ code, you will probably find it more convenient to design your user interfaces with <literal>Glade</literal> and load them at runtime with <literal>Gtk::Builder</literal>. See the <link linkend="chapter-builder">Glade and Gtk::Builder</link> chapter.Although you can theoretically implement your own Model, you will normally use either the <classname>ListStore</classname> or <classname>TreeStore</classname> model classes.Although you can use C++ code to instantiate and arrange widgets, this can soon become tedious and repetitive. And it requires a recompilation to show changes. The <application>Glade</application> application allows you to layout widgets on screen and then save an XML description of the arrangement. Your application can then use the <application>Gtk::Builder</application> API to load that XML file at runtime and obtain a pointer to specifically named widget instances.Although your container might have its own method to set the child widgets, you should still provide an implementation for the virtual <methodname>on_add()</methodname> and <methodname>on_remove()</methodname> methods from the base class, so that the add() and remove() methods will do something appropriate if they are called.Although, in most cases, the programmer will prefer to allow containers to automatically destroy their children using <function>Gtk::manage()</function> (see below), the programmer is not required to use <function>Gtk::manage()</function>. The traditional <literal>new</literal> and <literal>delete</literal> operators may also be used. <placeholder-1/> Here, the programmer deletes <varname>pButton</varname> to prevent a memory leak.An <classname>Assistant</classname> splits a complex operation into steps. Each step is a page, containing a header, a child widget and an action area. The Assistant's action area has navigation buttons which update automatically depending on the type of the page, set with <methodname>set_page_type()</methodname>.An <classname>Entry</classname> widget can show a progress bar inside the text area, under the entered text. The progress bar will be shown if the <methodname>set_progress_fraction()</methodname> or <methodname>set_progress_pulse_step()</methodname> methods are called.An <classname>InfoBar</classname> may show small items of information or ask brief questions. Unlike a <classname>Dialog</classname>, it appears at the top of the current window instead of opening a new window. Its API is very similar to the <link linkend="chapter-dialogs">Gtk::Dialog</link> API.An improved Hello WorldAnastasovAnd here's an excerpt from a <application>gdb</application> session. <placeholder-1/> The exception is caught in <application>glibmm</application>, and the program ends with a call to <function>g_error()</function>. Other exceptions may result in different behaviour, but in any case the exception from a signal handler is caught in <application>glibmm</application> or <application>gtkmm</application>, and <application>gdb</application> can't see where it was thrown.Another thing to note about this example is that we made the call to <methodname>connect()</methodname> twice for the same signal object. This is perfectly fine - when the button is clicked, both signal handlers will be called.Another way of destroying the connection is your signal handler. It has to be of the type <classname>sigc::slot&lt;bool&gt;</classname>. As you see from the definition your signal handler has to return a value of the type <literal>bool</literal>. A definition of a sample method might look like this: <placeholder-1/>Another workaround is to add a <function>*_construct()</function> function that the C++ constructor can call after instantiating its own type. For instance, <placeholder-1/>Any <classname>sigc::connection</classname> object should be regarded as owned by the thread in which the method returning the <classname>sigc::connection</classname> object was called. Only that thread should call <classname>sigc::connection</classname> methods on the object.Any additional non-generated <filename>.h</filename> and <filename>.cc</filename> source files may be placed in <filename>skeleton/skeletonmm/</filename> and listed in <filename>skeleton/skeletonmm/filelist.am</filename>, typically in the <varname>files_extra_h</varname> and <varname>files_extra_cc</varname> variables.Application LifetimeApplying TagsAs before, almost all of the interesting stuff is done in the draw signal handler <methodname>on_draw()</methodname>. Before we dig into the draw signal handler, notice that the constructor for the <classname>Clock</classname> widget connects a handler function <methodname>on_timeout()</methodname> to a timer with a timeout period of 1000 milliseconds (1 second). This means that <methodname>on_timeout()</methodname> will get called once per second. The sole responsibility of this function is to invalidate the window so that <application>gtkmm</application> will be forced to redraw it.As mentioned above, each <classname>TextView</classname> has a <classname>TextBuffer</classname>, and one or more <classname>TextView</classname>s can share the same <classname>TextBuffer</classname>.As mentioned earlier, <classname>Gtk::Adjustment</classname> can emit signals. This is, of course, how updates happen automatically when you share an <classname>Adjustment</classname> object between a <classname>Scrollbar</classname> and another adjustable widget; all adjustable widgets connect signal handlers to their adjustment's <literal>value_changed</literal> signal, as can your program.As well as renaming the directories, we should rename some of the source files. For instance: <placeholder-1/> A number of the skeleton files must still be filled in with project-specific content later.As will be explained in the <link linkend="chapter-adjustment">Adjustment</link> section, all Range widgets are associated with a <classname>Adjustment</classname> object. To change the lower, upper, and current values used by the widget you need to use the methods of its <classname>Adjustment</classname>, which you can get with the <methodname>get_adjustment()</methodname> method. The <classname>Range</classname> widgets' default constructors create an <classname>Adjustment</classname> automatically, or you can specify an existing <classname>Adjustment</classname>, maybe to share it with another widget. See the <link linkend="chapter-adjustment">Adjustments</link> section for further details.As with <classname>Scrollbar</classname>s, the orientation can be either horizontal or vertical. The default constructor creates an <classname>Adjustment</classname> with all of its values set to <literal>0.0</literal>. This isn't useful so you will need to set some <classname>Adjustment</classname> details to get meaningful behaviour.Aside from the fact that connected slots always execute in the receiver thread, <classname>Glib::Dispatcher</classname> objects are similar to <classname>sigc::signal&lt;void&gt;</classname> objects. They therefore cannot pass unbound arguments nor return a value. The best way to pass unbound arguments is with a thread-safe (asynchronous) queue. At the time of writing <application>glibmm</application> does not have one, although most people writing multi-threaded code will have one available to them (they are relatively easy to write although there are subtleties in combining thread safety with strong exception safety).AspectFrameAssistantAssuming the displayed size of stringsAsynchronous operationsAt install time, the <filename>.po</filename> files are converted to a binary format (with the extension <filename>.mo</filename>) and placed in a system-wide directory for locale files, for example <filename>/usr/share/locale/</filename>.At the least, the <function>_new()</function> function should not use any private API (functions that are only in a .c file). Even when there are no functions, we can sometimes reimplement 2 or 3 lines of code in a <function>_new()</function> function as long as those lines of code use API that is available to us.At the moment, we have separate tools for generating different parts of these <filename>.defs</filename>, so we split them up into separate files. For instance, in the <filename>gtk/src</filename> directory of the <application>gtkmm</application> sources, you will find these files: <placeholder-1/>Automatically-stored editable cells.Basic Type equivalentsBasic TypesBasicsBecause the user may enter arbitrary text, an active model row isn't enough to tell us what text the user has entered. Therefore, you should retrieve the <classname>Entry</classname> widget with the <methodname>ComboBox::get_entry()</methodname> method and call <methodname>get_text()</methodname> on that.Because this automatic transformation is not always appropriate, you might want to provide hand-written text for a particular method. You can do this by copying the XML node for the function from your <filename>something_docs.xml</filename> file to the <filename>something_docs_override.xml</filename> file and changing the contents.Before attempting to install <application>gtkmm</application> 3.0, you might first need to install these other packages.Below is a short example to illustrate these functions. This example makes use of the Frame widget to better demonstrate the label styles. (The Frame widget is explained in the <link linkend="sec-frame">Frame</link> section.) It is possible that the first character in <literal>m_Label_Normal</literal> is shown underlined only when you press the <keycap>Alt</keycap> key.BernhardBesides indicating the amount of progress that has occured, the progress bar can also be used to indicate that there is some activity; this is done by placing the progress bar in <emphasis>activity mode</emphasis>. In this mode, the progress bar displays a small rectangle which moves back and forth. Activity mode is useful in situations where the progress of an operation cannot be calculated as a value range (e.g., receiving a file of unknown length).Binding extra argumentsBjarne Stroustrup, "The C++ Programming Language" Forth Edition - section 34.3Box Packing 1Box Packing 2BoxesBuilding <application>gtkmm</application> on Win32But unlike most smartpointers, you can't use the * operator to access the underlying instance.But unlike normal pointers, <classname>RefPtr</classname>s are automatically initialized to null so you don't need to remember to do that yourself.ButtonButton boxes are a convenient way to quickly arrange a group of buttons. Their orientation can be either horizontal or vertical.Button boxes support several layout styles. The style can be retrieved and changed using <methodname>get_layout()</methodname> and <methodname>set_layout()</methodname>.ButtonBoxButtonBoxesButtonsButtons are added to a <classname>ButtonBox</classname> with the <methodname>add()</methodname> method.By convention, glib/GTK+-style objects have <function>*_new()</function> functions, such as <function>example_widget_new()</function> that do nothing more than call <function>g_object_new()</function> and return the result. The input parameters are supplied to <function>g_object_new()</function> along with the names of the properties for which they are values. For instance, <placeholder-1/>By convention, structs are declared in glib/GTK+-style headers like so: <placeholder-1/>By default, <application>gtkmm</application> will be installed under the <filename>/usr/local</filename> directory. On some systems you may need to install to a different location. For instance, on Red Hat Linux systems you might use the <literal>--prefix</literal> option with configure, like so: <screen>
# ./configure --prefix=/usr
</screen>By default, <application>jhbuild</application>'s configuration is configured to install all software built with <application>jhbuild</application> under the <filename>/opt/gnome</filename> prefix. You can choose a different prefix, but it is recommended that you keep this prefix different from other software that you've installed (don't set it to <filename>/usr</filename>!) If you've followed the jhbuild instructions then this prefix belongs to your user, so you don't need to run jhbuild as <literal>root</literal>.By default, <methodname>PrintOperation::run()</methodname> returns when a print operation is completed. If you need to run a non-blocking print operation, call <methodname>PrintOperation::set_allow_async()</methodname>. Note that <methodname>set_allow_async()</methodname> is not supported on all platforms, however the <literal>done</literal> signal will still be emitted.By default, only single rows can be selected, but you can allow multiple selection by setting the mode, like so: <placeholder-1/>By default, your signal handlers are called after any previously-connected signal handlers. However, this can be a problem with the X Event signals. For instance, the existing signal handlers, or the default signal handler, might return <literal>true</literal> to stop other signal handlers from being called. To specify that your signal handler should be called before the other signal handlers, so that it will always be called, you can specify <literal>false</literal> for the optional <literal>after</literal> parameter. For instance, <placeholder-1/>By deriving directly from <classname>Gtk::Widget</classname> you can do all the drawing for your widget directly, instead of just arranging child widgets. For instance, a <classname>Gtk::Label</classname> draws the text of the label, but does not do this by using other widgets.By overriding <methodname>forall_vfunc()</methodname> you can allow applications to operate on all of the container's child widgets. For instance, <methodname>show_all_children()</methodname> uses this to find all the child widgets and show them.C programmers use <function>sprintf()</function> to compose and concatenate strings. C++ favours streams, but unfortunately, this approach makes translation difficult, because each fragment of text is translated separately, without allowing the translators to rearrange them according to the grammar of the language.C typeC++ typeCairo and PangoCall <methodname>show()</methodname> to display the widget.CastingCells in a <classname>TreeView</classname> can be edited in-place by the user. To allow this, use the <classname>Gtk::TreeView</classname><methodname>insert_column_editable()</methodname> and <methodname>append_column_editable()</methodname> methods instead of <methodname>insert_column()</methodname> and <methodname>append_column()</methodname>. When these cells are edited the new values will be stored immediately in the Model. Note that these methods are templates which can only be instantiated for simple column types such as <classname>Glib::ustring</classname>, int, and long.Changes in <application>gtkmm</application> 3Changing the layout of a window "on the fly", to make some extra widgets appear, for instance, is complex. It requires tedious recalculation of every widget's position.Changing the selectionChapter on "Drawing with Cairo".Chapter on "Multi-threaded programs".Chapter on "Printing".Chapter on "Recent Files".Chapter on "Timeouts".Chapter on "Working with gtkmm's Source Code".Chapter on Keyboard Events.CheckButtonCheckboxesChecking for nullChild widgets can span multiple rows or columns, using <methodname>attach()</methodname>, or added next to an existing widget inside the grid with <methodname>attach_next_to()</methodname>. Individual rows and columns of the grid can be set to have uniform height or width with <methodname>set_row_homogeneous()</methodname> and <methodname>set_column_homogeneous()</methodname>.ChrisClass Scope widgetsClass macrosClipboard - IdealClipboard - SimpleColorChooserDialogCombo BoxesComboBoxComboBox with EntryComboBox with an EntryComboBoxTextComboBoxText with EntryComparison with other signalling systemsComposition of stringsConnect any signals you wish to use to the appropriate handlers.Connecting Plugs and SocketsConnecting signal handlersConst Objects used via <classname>RefPtr</classname>: If the object should not be changed by the function, then make sure that the object is const, even if the <classname>RefPtr</classname> is already const. For instance, <code>const Glib::RefPtr&lt;const Gtk::FileFilter&gt;&amp; filter</code>.ConstnessConstructor macrosConstructorsContainer WidgetsContrary to other events, keyboard events are first sent to the toplevel window (<classname>Gtk::Window</classname>), where it will be checked for any keyboard shortcuts that may be set (accelerator keys and mnemonics, used for selecting menu items from the keyboard). After this (and assuming the event wasn't handled), it is sent to the widget which has focus, and the propagation begins from there.ContributingCopyCopyingCopying the skeleton projectCreate a <classname>Plug</classname> independantly from any particular <classname>Socket</classname> and pass the ID of the <classname>Plug</classname> to other processes that need to use it. The ID of the <classname>Plug</classname> can be associated with a particular <classname>Socket</classname> object using the <methodname>Socket::add_id()</methodname> function. This is the approach used in the example below.Create a <classname>Socket</classname> object in one process and pass the ID of that <classname>Socket</classname> to another process so that it can create a <classname>Plug</classname> object by specifying the given <classname>Socket</classname> ID in its constructor. There is no way to assign a <classname>Plug</classname> to a particular <classname>Socket</classname> after creation, so you must pass the <classname>Socket</classname> ID to the <classname>Plug</classname>'s constructor.Create a sub-directory named <literal>po</literal> in your project's root directory. This directory will eventually contain all of your translations. Within it, create a file named <literal>LINGUAS</literal> and a file named <literal>POTFILES.in</literal>. It is common practice to also create a <literal>ChangeLog</literal> file in the <literal>po</literal> directory so that translators can keep track of translation changes.Create your own signals instead of passing pointers around. Objects can communicate with each other via signals and signal handlers. This is much simpler than objects holding pointers to each other and calling each other's methods. <application>gtkmm</application>'s classes uses special versions of <classname>sigc::signal</classname>, but you should use normal <classname>sigc::signal</classname>s, as described in the <application>libsigc++</application> documentation.Creating .hg and .ccg filesCreating an AdjustmentCreating your own signalsCummingCurrently, <application>gettext</application> does not support non-ASCII characters (i.e. any characters with a code above 127) in source code. For instance, you cannot use the copyright sign (©).Custom ContainerCustom ContainersCustom WidgetCustom WidgetsDISTCLEANFILES = ... intltool-extract \
                 intltool-merge \
                 intltool-update \
                 po/.intltool-merge-cacheDanielDavidDeclare a variable of the type of <classname>Widget</classname> you wish to use, generally as member variable of a derived container class. You could also declare a pointer to the widget type, and then create it with <literal>new</literal> in your code. Even when using the widget via a pointer, it's still probably best to make that pointer a member variable of a container class so that you can access it later.Default formattingDefine <literal>INTLTOOL_FILES</literal> as: <placeholder-1/>Defines a custom clipboard target, though the format of that target is still text.DependenciesDereferencingDesigners without programming skills can create and edit UIs.DialogsDialogs are used as secondary windows, to provide specific information or to ask questions. <classname>Gtk::Dialog</classname> windows contain a few pre-packed widgets to ensure consistency, and a <methodname>run()</methodname> method which blocks until the user dismisses the dialog.Different applications contain different types of data, and they might make that data available in a variety of formats. <application>gtkmm</application> calls these data types <literal>target</literal>s.Different join types in CairoDisconnecting signal handlersDiscovering the available targetsDo an extra <function>reference()</function> on the return value of an overridden <function>something_vfunc()</function> function in the C callback function, in case the calling C function expects it to provide a reference.Do an extra <function>reference()</function> on the return value of the <function>on_something()</function> virtual method, in case the C function does not provide a reference.Do an extra <function>reference()</function> on the return value of the <function>something_vfunc()</function> function, in case the virtual C function does not provide a reference.Do an extra <function>reference()</function> on the return value, in case the C function does not provide a reference.Do not generate a C callback function for the signal. Use this when you must generate the callback function by hand.Do not generate a C callback function for the vfunc. Use this when you must generate the callback function by hand.Do not generate a definition of the vfunc in the <filename>.cc</filename> file. Use this when you must generate the vfunc by hand.Do not generate an <function>on_something()</function> virtual method to allow easy overriding of the default signal handler. Use this when adding a signal with a default signal handler would break the ABI by increasing the size of the class's virtual function table.DocumentationDocumentation build structureDrag and DropDragContextDrawing Arcs and CirclesDrawing Area - ArcsDrawing Area - ImageDrawing Area - LinesDrawing Area - TextDrawing Area - Thin LinesDrawing Curved LinesDrawing ImagesDrawing Straight LinesDrawing TextDrawing Text with PangoDrawing counter-clockwiseDrawing thin linesDrawing with relative coordinatesDuring a <literal>move</literal>, the source widget will also emit this signal: <placeholder-1/>Dynamic allocation with manage() and add()Dynamic allocation with new and deleteEach <classname>Cairo::Context</classname> is associated with a particular <classname>Gdk::Window</classname>, so the first line of the above example creates a <classname>Gtk::DrawingArea</classname> widget and the second line uses its associated <classname>Gdk::Window</classname> to create a <classname>Cairo::Context</classname> object. The final two lines change the graphics state of the context.Each <classname>Gtk::TextBuffer</classname> uses a <classname>Gtk::TextBuffer::TagTable</classname>, which contains the <classname>Tag</classname>s for that buffer. 2 or more <classname>TextBuffer</classname>s may share the same <classname>TagTable</classname>. When you create <classname>Tag</classname>s you should add them to the <classname>TagTable</classname>. For instance:Each <classname>Gtk::TreeView</classname> has an associated <classname>Gtk::TreeModel</classname>, which contains the data displayed by the <classname>TreeView</classname>. Each <classname>Gtk::TreeModel</classname> can be used by more than one <classname>Gtk::TreeView</classname>. For instance, this allows the same underlying data to be displayed and edited in 2 different ways at the same time. Or the 2 Views might display different columns from the same Model data, in the same way that 2 SQL queries (or "views") might show different fields from the same database table.Each item in the list of recently used files is identified by its URI, and can have associated metadata. The metadata can be used to specify how the file should be displayed, a description of the file, its mime type, which application registered it, whether it's private to the registering application, and several other things.Each line contains one horizontal <classname>Box</classname> with several buttons. Each of the buttons on a line is packed into the <classname>Box</classname> with the same arguments to the <methodname>pack_start()</methodname> method.Editable CellsElstnerEmitted when the button is pressed and released.Emitted when the button is pressed.Emitted when the button is released.Emitted when the mouse pointer leaves the button's window.Emitted when the mouse pointer moves over the button's window.EntryEntry CompletionEntry Completion ExampleEntry Icon ExampleEntry IconsEntry ProgressEntry Progress ExampleEntry widgets allow the user to enter text. You can change the contents with the <methodname>set_text()</methodname> method, and read the current contents with the <methodname>get_text()</methodname> method.Entry with IconEntry with Progress BarEnumerations.Event PropagationEvent propagation means that, when an event is emitted on a particular widget, it can be passed to its parent widget (and that widget can pass it to its parent, and so on) and, if the parent has an event handler, that handler will be called.EventBoxExampleExample Application: Creating a Clock with CairoExamplesExceptions in signal handlersExpecting UTF8Export to PDFExtending the print dialogFerreiraFileChooserFileChooserDialogFiltering Recent FilesFinally, check the status. For instance, <placeholder-1/>Finally, to let your program use the translation for the current locale, add this code to the beginning of your <filename>main.cc</filename> file, to initialize gettext. <placeholder-1/>First create the <classname>Action</classname>s and add them to an <classname>ActionGroup</classname>, with <methodname>ActionGroup::add()</methodname>.First we instantiate an object stored in a <classname>RefPtr</classname> smartpointer called <literal>app</literal>. This is of type <classname>Gtk::Application</classname>. Every <application>gtkmm</application> program must have one of these. We pass our command-line arguments to its create() method. It takes the arguments it wants, and leaves you the rest, as we described earlier.First, let's look at a simple example where an exception is thrown from a normal function (no signal handler). <placeholder-1/>FontChooserDialogFor a CellRendererToggle, you would set the <emphasis>activatable</emphasis> property instead.For any of the <classname>RecentChooser</classname> classes, if you don't wish to display all of the items in the list of recent files, you can filter the list to show only those that you want. You can filter the list with the help of the <classname>RecentFilter</classname> class. This class allows you to filter recent files by their name (<methodname>add_pattern()</methodname>), their mime type (<methodname>add_mime_type()</methodname>), the application that registered them (<methodname>add_application()</methodname>), or by a custom filter function (<methodname>add_custom()</methodname>). It also provides the ability to filter based on how long ago the file was modified and which groups it belongs to.For each page that needs to be rendered, the following signals are emitted: <placeholder-1/>For example, for <classname>Pango::Analysis</classname> in <filename>item.hg</filename>: <placeholder-1/>For example, from <filename>icontheme.hg</filename>: <placeholder-1/>For example, if there was a C function that returned a <type>GtkWidget*</type> and for some reason, instead of having the C++ method also return the widget, it was desirable to have the C++ method place the widget in a specified output parameter, an initialization macro such as the following would be necessary: <placeholder-1/>For example, in <filename>rectangle.hg</filename>: <placeholder-1/>For example, in Pangomm, <filename>layoutline.hg</filename>: <placeholder-1/>For information about implementing your own signals rather than just connecting to the existing <application>gtkmm</application> signals, see the <link linkend="chapter-custom-signals">appendix</link>.For instance,For instance, <application>gedit</application> can supply and receive the <literal>"UTF8_STRING"</literal> target, so you can paste data into <application>gedit</application> from any application that supplies that target. Or two different image editing applications might supply and receive a variety of image formats as targets. As long as one application can receive one of the targets that the other supplies then you will be able to copy data from one to the other.For instance, <placeholder-1/>For instance, for <classname>Gdk::Rectangle</classname>: <placeholder-1/>For instance, for <classname>Pango::AttrIter</classname>: <placeholder-1/>For instance, for <classname>Pango::Coverage</classname>: <placeholder-1/>For instance, for a CellRendererText, you would set the cell's <emphasis>editable</emphasis> property to true, like so:For instance, from <classname>Gdk::RGBA</classname>: <placeholder-1/>For instance, from <filename>accelgroup.hg</filename>: <placeholder-1/>For instance, from <filename>button.hg</filename>: <placeholder-1/>For instance, from <filename>buttonbox.hg</filename>: <placeholder-1/>For instance, from <filename>celleditable.hg</filename>: <placeholder-1/>For instance, from <filename>container.hg</filename>: <placeholder-1/>For instance, from <filename>entry.hg</filename>: <placeholder-1/>For instance, from <filename>enums.hg</filename>: <placeholder-1/>For instance, from <filename>pixbuf.hg</filename>: <placeholder-1/>For instance, from <filename>widget.hg</filename>: <placeholder-1/>For instance, this code would be problematic:For instance, to create a signal that sends 2 parameters, a <type>bool</type> and an <type>int</type>, just declare a <classname>sigc::signal</classname>, like so: <placeholder-1/>For instance:For more detailed information about signals, see the <link linkend="chapter-signals">appendix</link>.For multiple-selection, you need to define a callback, and give it to <methodname>selected_foreach()</methodname>, <methodname>selected_foreach_path()</methodname>, or <methodname>selected_foreach_iter()</methodname>, like so:For reference, it is possible to generate a file which contains all strings which appear in your code, even if they are not marked for translation, together with file name and line number references. To generate such a file named <literal>my-strings</literal>, execute the following command, within the source code directory: <placeholder-1/>For single-selection, you can just call <methodname>get_selected()</methodname>, like so:For the input of passwords, passphrases and other information you don't want echoed on the screen, calling <methodname>set_visibility()</methodname> with <literal>false</literal> will cause the text to be hidden.FrameFrames can enclose one or a group of widgets within a box, optionally with a title. For instance, you might place a group of <classname>RadioButton</classname>s or <classname>CheckButton</classname>s in a <classname>Frame</classname>.From time to time, it may be useful to be able to embed a widget from another application within your application. <application>gtkmm</application> allows you to do this with the <classname>Gtk::Socket</classname> and <classname>Gtk::Plug</classname> classes. It is not anticipated that very many applications will need this functionality, but in the rare case that you need to display a widget that is running in a completely different process, these classes can be very helpful.Full ExampleFunction scope widgetsGTK+ 3.0GTK+ and <application>gtkmm</application> were designed to work well with Microsoft Windows, and the developers encourage its use on the win32 platform. However, Windows has no standard installation system for development libraries. Please see the <ulink url="http://live.gnome.org/gtkmm/MSWindows">Windows Installation</ulink> page for Windows-specific installation instructions and notes.GTK+ uses the <ulink url="http://cairographics.org">Cairo</ulink> drawing API. With <application>gtkmm</application>, you may use the <ulink url="http://www.cairographics.org/cairomm/">cairomm</ulink> C++ API for cairo.Generate a declaration of the <function>on_something()</function> virtual method in the <filename>.h</filename> file, but do not generate a definition in the <filename>.cc</filename> file. Use this when you must generate the definition by hand.Generating the .defs files.Generating the enums .defsGenerating the methods .defsGenerating the signals and properties .defsGeneration of the source code for a gtkmm-style wrapper API requires use of tools such as <command>gmmproc</command> and <filename>generate_wrap_init.pl</filename>. In theory you could write your own build files to use these appropriately, but a much better option is to make use of the build infrastructure provided by the mm-common module. To get started, it helps a lot to pick an existing binding module as an example to look at.Get the data from the widgets in the <literal>custom_widget_apply</literal> signal handler.Getting help with translationsGetting valuesGive all command-line options to <methodname>Gtk::Application::create()</methodname> and add the flag <literal>Gio::APPLICATION_HANDLES_COMMAND_LINE</literal>. Connect a signal handler to the <literal>command_line</literal> signal, and handle the command-line options in the signal handler.Glade and Gtk::BuilderGlib::IO_ERR - Call your method when an error has occurred on the file descriptor.Glib::IO_HUP - Call your method when hung up (the connection has been broken usually for pipes and sockets).Glib::IO_IN - Call your method when there is data ready for reading on your file descriptor.Glib::IO_OUT - Call your method when the file descriptor is ready for writing.Glib::IO_PRI - Call your method when the file descriptor has urgent data to be read.Glib::RefPtr&lt;Gtk::Adjustment&gt; Gtk::Adjustment::create(
  double value,
  double lower,
  double upper,
  double step_increment = 1,
  double page_increment = 10,
  double page_size = 0);Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");Glib::RefPtr&lt;Gtk::Clipboard&gt; refClipboard = Gtk::Clipboard::get();

//Targets:
std::vector&lt;Gtk::TargetEntry&gt; targets;
targets.push_back( Gtk::TargetEntry("example_custom_target") );
targets.push_back( Gtk::TargetEntry("UTF8_STRING") );

refClipboard-&gt;set( targets,
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_get),
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_clear) );Glib::RefPtr&lt;Gtk::ListStore&gt; refListStore =
    Gtk::ListStore::create(m_Columns);Glib::RefPtr&lt;Gtk::RecentInfo&gt; info;
try
{
  info = recent_manager-&gt;lookup_item(uri);
}
catch(const Gtk::RecentManagerError&amp; ex)
{
  std::cerr &lt;&lt; "RecentManagerError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
}
if (info)
{
  // item was found
}Glib::RefPtr&lt;Gtk::RecentManager&gt; recent_manager = Gtk::RecentManager::get_default();
recent_manager-&gt;add_item(uri);Glib::RefPtr&lt;Gtk::TextBuffer::Mark&gt; refMark =
    refBuffer-&gt;create_mark(iter);Glib::RefPtr&lt;Gtk::TextBuffer::Tag&gt; refTagMatch =
    Gtk::TextBuffer::Tag::create();
refTagMatch-&gt;property_background() = "orange";Glib::RefPtr&lt;Gtk::TextBuffer::TagTable&gt; refTagTable =
    Gtk::TextBuffer::TagTable::create();
refTagTable-&gt;add(refTagMatch);
//Hopefully a future version of <application>gtkmm</application> will have a set_tag_table() method,
//for use after creation of the buffer.
Glib::RefPtr&lt;Gtk::TextBuffer&gt; refBuffer =
    Gtk::TextBuffer::create(refTagTable);Glib::RefPtr&lt;Gtk::TextChildAnchor&gt; refAnchor =
    refBuffer-&gt;create_child_anchor(iter);Glib::RefPtr&lt;Gtk::TreeModelSort&gt; sorted_model =
    Gtk::TreeModelSort::create(model);
sorted_model-&gt;set_sort_column(columns.m_col_name, Gtk::SORT_ASCENDING);
treeview.set_model(sorted_model);Glib::RefPtr&lt;Gtk::TreeSelection&gt; refTreeSelection =
    m_TreeView.get_selection();Glib::RefPtr&lt;Gtk::UIManager&gt; m_refUIManager =
    Gtk::UIManager::create();
m_refUIManager-&gt;insert_action_group(m_refActionGroup);
add_accel_group(m_refUIManager-&gt;get_accel_group());Glib::ustringGlib::ustring and std::iostreamsGlib::ustring strText = row[m_Columns.m_col_text];
int number = row[m_Columns.m_col_number];Glib::ustring ui_info =
    "&lt;ui&gt;"
    "  &lt;menubar name='MenuBar'&gt;"
    "    &lt;menu action='MenuFile'&gt;"
    "      &lt;menuitem action='New'/&gt;"
    "      &lt;menuitem action='Open'/&gt;"
    "      &lt;separator/&gt;"
    "      &lt;menuitem action='Quit'/&gt;"
    "    &lt;/menu&gt;"
    "    &lt;menu action='MenuEdit'&gt;"
    "      &lt;menuitem action='Cut'/&gt;"
    "      &lt;menuitem action='Copy'/&gt;"
    "      &lt;menuitem action='Paste'/&gt;"
    "    &lt;/menu&gt;"
    "  &lt;/menubar&gt;"
    "  &lt;toolbar  name='ToolBar'&gt;"
    "    &lt;toolitem action='Open'/&gt;"
    "    &lt;toolitem action='Quit'/&gt;"
    "  &lt;/toolbar&gt;"
    "&lt;/ui&gt;";

m_refUIManager-&gt;add_ui_from_string(ui_info);Glib::ustring ui_info =
    "&lt;ui&gt;"
    "  &lt;popup name='PopupMenu'&gt;"
    "    &lt;menuitem action='ContextEdit'/&gt;"
    "    &lt;menuitem action='ContextProcess'/&gt;"
    "    &lt;menuitem action='ContextRemove'/&gt;"
    "  &lt;/popup&gt;"
    "&lt;/ui&gt;";

m_refUIManager-&gt;add_ui_from_string(ui_info);GridGroupsGtk::Alignment
Gtk::Arrow
Gtk::AspectFrame
Gtk::Bin
Gtk::Box
Gtk::Button
Gtk::CheckButton
Gtk::Fixed
Gtk::Frame
Gtk::Grid
Gtk::Image
Gtk::Label
Gtk::MenuItem
Gtk::Notebook
Gtk::Paned
Gtk::RadioButton
Gtk::Range
Gtk::ScrolledWindow
Gtk::Separator
Gtk::Table (deprecated from <application>gtkmm</application> version 3.4)
Gtk::ToolbarGtk::Application and command-line optionsGtk::Box(Gtk::Orientation orientation = Gtk::ORIENTATION_HORIZONTAL, int spacing = 0);
void set_spacing(int spacing);
void set_homogeneous(bool homogeneous = true);Gtk::Button* pButton = new Gtk::Button("_Something", true);Gtk::CellRendererToggle* pRenderer =
    Gtk::manage( new Gtk::CellRendererToggle() );
pRenderer-&gt;signal_toggled().connect(
    sigc::bind( sigc::mem_fun(*this,
        &amp;Example_TreeView_TreeStore::on_cell_toggled), m_columns.dave)
);Gtk::ComboBox now derives from CellLayout, allowing easier layout and alignment of its <classname>Gtk::CellRenderer</classname>s.Gtk::DrawingArea myArea;
Cairo::RefPtr&lt;Cairo::Context&gt; myContext = myArea.get_window()-&gt;create_cairo_context();
myContext-&gt;set_source_rgb(1.0, 0.0, 0.0);
myContext-&gt;set_line_width(2.0);Gtk::Entry* entry = m_Combo.get_entry();
if (entry)
{
  // The Entry shall receive focus-out events.
  entry-&gt;add_events(Gdk::FOCUS_CHANGE_MASK);

  // Alternatively you can connect to m_Combo.signal_changed().
  entry-&gt;signal_changed().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_entry_changed) );

  entry-&gt;signal_activate().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_entry_activate) );

  entry-&gt;signal_focus_out_event().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_entry_focus_out_event) );
}Gtk::EventBox();Gtk::Label support some simple formatting, for instance allowing you to make some text bold, colored, or larger. You can do this by providing a string to <methodname>set_markup()</methodname>, using the <ulink url="http://developer.gnome.org/pango/unstable/PangoMarkupFormat.html">Pango Markup syntax</ulink>. For instance, <code> &lt;b&gt;bold text&lt;/b&gt; and &lt;s&gt;strikethrough text&lt;/s&gt; </code> .Gtk::TreeModel::Children children = row.children();Gtk::TreeModel::Row row = *iter;Gtk::TreeModel::Row row = m_refModel-&gt;children()[5]; //The fifth row.
if(row)
  refTreeSelection-&gt;select(row);Gtk::TreeModel::iterator iter = m_Combo.get_active();
if(iter)
{
  Gtk::TreeModel::Row row = *iter;

  //Get the data for the selected row, using our knowledge
  //of the tree model:
  int id = row[m_Columns.m_col_id];
  set_something_id_chosen(id); //Your own function.
}
else
  set_nothing_chosen(); //Your own function.Gtk::TreeModel::iterator iter = m_refListStore-&gt;append();Gtk::TreeModel::iterator iter = m_refModel-&gt;children().begin()
if(iter)
  refTreeSelection-&gt;select(iter);Gtk::TreeModel::iterator iter_child =
    m_refTreeStore-&gt;append(row.children());Gtk::TreeView::Column* pColumn =
  Gtk::manage(new Gtk::TreeView::Column("Icon Name"));

// m_columns.icon and m_columns.iconname are columns in the model.
// pColumn is the column in the TreeView:
pColumn-&gt;pack_start(m_columns.icon, /* expand= */ false);
pColumn-&gt;pack_start(m_columns.iconname);

m_TreeView.append_column(*pColumn);Gtk::TreeView::Column* pColumn = treeview.get_column(0);
if(pColumn)
  pColumn-&gt;set_sort_column(m_columns.m_col_id);Gtk::Widget* pMenubar = m_refUIManager-&gt;get_widget("/MenuBar");
pBox-&gt;add(*pMenuBar, Gtk::PACK_SHRINK);Gtk::Window window;
window.set_default_size(200, 200);Hand-coded source filesHand-coding constructorsHandle the options in <function>main()</function> and hide them from <classname>Gtk::Application</classname> by setting <literal>argc = 1</literal> in the call to <methodname>Gtk::Application::create()</methodname>.Handling <literal>button_press_event</literal>Headers and LinkingHello WorldHello World 2Hello World in <application>gtkmm</application>HelloWorld::HelloWorld()
:
  m_button ("Hello World")
{
  set_border_width(10);
  m_button.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;HelloWorld::on_button_clicked));
  add(m_button);.
  m_button.show();
}Here are some examples of normal C++ memory management:Here is a list of some of these Widgets:Here is a simple example that packs 100 toggle buttons into a ScrolledWindow. Try resizing the window to see the scrollbars react.Here is a small bit of code to tie it all together: (Note that usually you wouldn't load the image every time in the draw signal handler! It's just shown here to keep it all together.)Here is a very simple example, demonstrating a drag and drop <literal>Copy</literal> operation:Here is an example callback method:Here is an example of a program that draws some text, some of it upside-down. The Printing chapter contains another <link linkend="sec-printing-example">example</link> of drawing text.Here is an example of a simple program that draws an image.Here is an excerpt from a <application>gdb</application> session. Only the most interesting parts of the output are shown. <placeholder-1/> You can see that the exception was thrown from <filename>without_signal.cc</filename>, line 6 (<code>throw "Something";</code>).Here is some example code from <filename>gtkmm/demos/gtk-demo/example_icontheme.cc</filename>, which has a pixbuf icon and a text name in the same column:Here is the source code for the example that produced the screenshots above. When you run this example, provide a number between 1 and 3 as a command-line option, to see different packing options in use.Here we define a new class called <classname>OverriddenButton</classname>, which inherits from <classname>Gtk::Button</classname>. The only thing we change is the <methodname>on_clicked()</methodname> method, which is called whenever <classname>Gtk::Button</classname> emits the <literal>clicked</literal> signal. This method prints "Hello World" to <literal>stdout</literal>, and then calls the original, overridden method, to let <classname>Gtk::Button</classname> do what it would have done had we not overridden.Here's a simple example: <placeholder-1/>Here's a slightly larger example of slots in action:Here's an example of a <classname>SpinButton</classname> in action:Here's an example of a signal handler being connected to a signal:Here's an example of a simple program that draws an arc, a circle and an ellipse into a drawing area.Here's an example of this technique:Here's the constructor for the <classname>Box</classname> widget, and methods that set per-container packing options: <placeholder-1/> Passing <literal>true</literal> to <methodname>set_homogeneous()</methodname> will cause all of the contained widgets to be the same size. <parameter>spacing</parameter> is a (minimum) number of pixels to leave between each widget.How gettext worksHow to use Git for GNOME translatorsHowever, <application>Glib</application> defines <function>gettext()</function> support macros which are shorter wrappers in an easy-to-use form. To use these macros, include <literal>&lt;glibmm/i18n.h&gt;</literal>, and then, for example, substitute: <placeholder-1/> with: <placeholder-2/>However, care is required when writing programs based on <application>gtkmm</application> using multiple threads of execution, arising from the fact that <application>libsigc++</application>, and in particular <classname>sigc::trackable</classname>, are not thread-safe. That's because none of the complex interactions that occur behind the scenes when using <application>libsigc++</application> are protected by a mutex or other means of synchronization. <placeholder-1/>However, this does not allow you any control of which items can be dragged, and where they can be dropped. If you need that extra control then you might create a derived <literal>Gtk::TreeModel</literal> from <literal>Gtk::TreeStore</literal> or <literal>Gtk::ListStore</literal> and override the <literal>Gtk::TreeDragSource::row_draggable()</literal> and <literal>Gdk::TreeDragDest::row_drop_possible()</literal> virtual methods. You can examine the <literal>Gtk::TreeModel::Path</literal>s provided and allow or disallow dragging or dropping by returning <literal>true</literal> or <literal>false</literal>.However, this is even simpler when using the <function>PKG_CHECK_MODULES()</function> macro in a standard configure.ac file with autoconf and automake. For instance: <placeholder-1/> This checks for the presence of gtkmm and defines MYAPP_LIBS and MYAPP_CFLAGS for use in your Makefile.am files.However, you might not want the new values to be stored immediately. For instance, maybe you want to restrict the input to certain characters or ranges of values.However, you probably already avoid bare char* arrays and pointer arithmetic by using <classname>std::string</classname>, so you just need to start using <classname>Glib::ustring</classname> instead. See the <link linkend="sec-basics-ustring">Basics</link> chapter about <classname>Glib::ustring</classname>.I've been embedded.
A plug was addedINTLTOOL_FILES = intltool-extract.in \
                 intltool-merge.in \
                 intltool-update.inIT_PROG_INTLTOOL([0.35.0])

GETTEXT_PACKAGE=programname
AC_SUBST(GETTEXT_PACKAGE)
AC_DEFINE_UNQUOTED([GETTEXT_PACKAGE], ["$GETTEXT_PACKAGE"],
                   [The domain to use with gettext])
AM_GLIB_GNU_GETTEXT

PROGRAMNAME_LOCALEDIR=[${datadir}/locale]
AC_SUBST(PROGRAMNAME_LOCALEDIR)IdealIdeally, we would like you to <ulink url="http://www.gtkmm.org/bugs.shtml">provide a patch</ulink> to the <filename>docs/tutorial/C/gtkmm-tutorial-in.xml</filename> file. This file is currently in the <literal>gtkmm-documentation</literal> module in GNOME git.Idle FunctionsIf a particular class object derives from <classname>sigc::trackable</classname>, only one thread should create <classname>sigc::slot</classname> objects representing any of the class's non-static methods by calling <function>sigc::mem_fun()</function>. The first thread to create such a slot should be regarded as owning the relevant object for the purpose of creating further slots referencing <emphasis>any</emphasis> of its non-static methods using that function, or nulling those slots by disconnecting them or destroying the trackable object.If a programmer does not need a class scope widget, a function scope widget may also be used. The advantages to function scope over class scope are the increased data hiding and reduced dependencies. <placeholder-1/>If a programmer does not need dynamic memory allocation, automatic widgets in class scope may be used. One advantage of automatic widgets in class scope is that memory management is grouped in one place. The programmer does not risk memory leaks from failing to <literal>delete</literal> a widget.If everything worked correctly, you should be able to build <application>gtkmm</application> and all of its dependencies from git by executing <command>jhbuild build</command> (or, if you didn't specify <application>gtkmm</application> in the <varname>modules</varname> variable, with the command <command>jhbuild build gtkmm</command>).If for some reason the <classname>Socket</classname> couldn't attach the <classname>Plug</classname>, the window would look something like this:If the enum is not a <classname>GType</classname>, you must pass a third parameter NO_GTYPE. This is the case when there is no <function>*_get_type()</function> function for the C enum, but be careful that you don't just need to include an extra header for that function. You should also file a bug against the C API, because all enums should be registered as GTypes.If there are many caught exceptions before the interesting uncaught one, this method can be tedious. It can be automated with the following <application>gdb</application> commands. <placeholder-1/> These commands will print a backtrace from each <code>throw</code> and continue. The backtrace from the last (or possibly the last but one) <code>throw</code> before the program stops, is the interesting one.If this is the first time you're using a program that uses the Recent Files framework, the dialog may be empty at first. Otherwise it should show the list of recently used documents registered by other applications.If you are interested in helping out with the development of <application>gtkmm</application>, or fixing a bug in <application>gtkmm</application>, you'll probably need to build the development version of <application>gtkmm</application>. However, you should not install a development version over your stable version. Instead, you should install it alongside your existing <application>gtkmm</application> installation, in a separate path.If you are using <application>gettext</application> directly, you can only mark strings for translation if they are in source code file. However, if you use <application>intltool</application>, you can mark strings for translation in a variety of other file formats, including <application>Glade</application> UI files, xml, <ulink url="http://standards.freedesktop.org/desktop-entry-spec/latest/">.desktop files</ulink> and several more. So, if you have designed some of the application UI in <application>Glade</application> then also add your <filename>.glade</filename> files to the list in <literal>POTFILES.in</literal>.If you call <methodname>Gtk::TreeView::set_reorderable()</methodname> then your TreeView's items can be moved within the treeview itself. This is demonstrated in the <classname>TreeStore</classname> example.If you copied the skeleton source tree in mm-common and substituted the placeholder text, then you will already have suitable <filename>Makefile.am</filename> and <filename>Doxyfile.in</filename> files. With the mm-common build setup, the list of Doxygen input files is not defined in the Doxygen configuration file, but passed along from <command>make</command> to the standard input of <command>doxygen</command>. The input file list is defined by the <varname>doc_input</varname> variable in the <filename>Makefile.am</filename> file.If you copy a <classname>RefPtr</classname>, for instance <placeholder-1/> , or if you pass it as a method argument or a return type, then <classname>RefPtr</classname> will do any necessary referencing to ensure that the instance will not be destroyed until the last <classname>RefPtr</classname> has gone out of scope.If you do decide to contribute, please post your contribution to the <application>gtkmm</application> mailing list at <ulink url="mailto:gtkmm-list@gnome.org">&lt;gtkmm-list@gnome.org&gt;</ulink>. Also, be aware that the entirety of this document is free, and any addition you provide must also be free. That is, people must be able to use any portion of your examples in their programs, and copies of this document (including your contribution) may be distributed freely.If you don't want to look for a specific URI, but instead want to get a list of all recently used items, <classname>RecentManager</classname> provides the <methodname>get_items()</methodname> function. The return value of this function is a <classname>std::vector</classname> of all recently used files. The following code demonstrates how you might get a list of recently used files:If you have created a <classname>Tag</classname> and added it to the <classname>TagTable</classname>, you may apply that tag to part of the <classname>TextBuffer</classname> so that some of the text is displayed with that formatting. You define the start and end of the range of text by specifying <classname>Gtk::TextBuffer::iterator</classname>s. For instance:If you pass <literal>true</literal> to the <methodname>set_activates_default()</methodname> method, pressing Enter in the <classname>Gtk::Entry</classname> will activate the default widget for the window containing the <classname>Gtk::Entry</classname>. This is especially useful in dialog boxes. The default widget is usually one of the dialog buttons, which e.g. will close the dialog box. To set a widget as the default widget, use <methodname>Gtk::Widget::set_can_default()</methodname> and <methodname>Gtk::Widget::grab_default()</methodname>.If you share an adjustment object between a Scrollbar and a TextView widget, manipulating the scrollbar will automagically adjust the TextView widget. You can set it up like this:If you try to draw one pixel wide lines, you may notice that the line sometimes comes up blurred and wider than it ought to be. This happens because Cairo will try to draw from the selected position, to both sides (half to each), so if you're positioned right on the intersection of the pixels, and want a one pixel wide line, Cairo will try to use half of each adjacent pixel, which isn't possible (a pixel is the smallest unit possible). This happens when the width of the line is an odd number of pixels (not just one pixel).If you want to help develop <application>gtkmm</application> or experiment with new features, you can also install <application>gtkmm</application> from git. Most users will never need to do this, but if you're interested in helping with <application>gtkmm</application> development, see the <link linkend="chapter-working-with-source">Working with gtkmm's Source Code</link> appendix.If you want to register a file with metadata, you can pass a <classname>RecentManager::Data</classname> parameter to <methodname>add_item()</methodname>. The metadata that can be set on a particular file item is as follows:If you want to specify a method that gets called when nothing else is happening, use the following:If you wish to learn more about smartpointers, you might look in these books: <placeholder-1/>If you've drawn a series of lines that form a path, you may want them to join together in a certain way. Cairo offers three different ways to join lines together: Miter, Bevel, and Round. These are show below:If you've never used a packing toolkit before, it can take some getting used to. You'll probably find, however, that you don't need to rely on visual form editors quite as much as you might with other toolkits.If your distribution does not provide a pre-built <application>gtkmm</application> package, or if you want to install a different version than the one provided by your distribution, you can also install <application>gtkmm</application> from source. The source code for <application>gtkmm</application> can be downloaded from <ulink url="http://www.gtkmm.org/"/>.If your program is free software, there is a whole <literal>GNOME</literal> subproject devoted to helping you make translations, the <ulink url="https://live.gnome.org/TranslationProject/"><literal>GNOME</literal> Translation Project</ulink>.Implementing custom logic for editable cells.In <filename>configure.ac</filename>, <placeholder-1/>In <filename>skeleton/skeletonmm/Makefile.am</filename> we must mention the correct values for the generic variables that are used elsewhere in the build system:In <filename>skeleton/src/Makefile.am</filename> we must mention the correct values for the generic variables that are used elsewhere in the build system:In addition to adding items to the list, you can also look up items from the list and modify or remove items.In addition to changing a file's URI, you can also remove items from the list, either one at a time or by clearing them all at once. The former is accomplished with <methodname>remove_item()</methodname>, the latter with <methodname>purge_items()</methodname>.In addition to drawing basic straight lines, there are a number of things that you can customize about a line. You've already seen examples of setting a line's color and width, but there are others as well.In addition to drawing straight lines Cairo allows you to easily draw curved lines (technically a cubic Bézier spline) using the <methodname>Cairo::Context::curve_to()</methodname> and <methodname>Cairo::Context::rel_curve_to()</methodname> functions. These functions take coordinates for a destination point as well as coordinates for two 'control' points. This is best explained using an example, so let's dive in.In general, gtkmm-style projects use Doxygen, which reads specially formatted C++ comments and generates HTML documentation. You may write these doxygen comments directly in the header files.In the <classname>Gtk::Window</classname>, we have also the default handler overridden (<methodname>on_key_release_event()</methodname>), and another handler being called before the default handler (<methodname>windowKeyReleaseBefore()</methodname>).In the <link linkend="sec-wrapping-hg-files">.hg and .ccg files</link> section you can learn about the syntax used in these files.In the example above we drew everything using absolute coordinates. You can also draw using relative coordinates. For a straight line, this is done with the function <methodname>Cairo::Context::rel_line_to()</methodname>.In the instructions below we will assume that you will not be using <application>gettext</application> directly, but <application>intltool</application>, which was written specifically for <literal>GNOME</literal>. <application>intltool</application> uses <function>gettext()</function>, which extracts strings from source code, but <application>intltool</application> can also combine strings from other files, for example from desktop menu details, and GUI resource files such as <application>Glade</application> files, into standard <application>gettext</application><filename>.pot/.po</filename> files.In the top-level Makefile.am: <placeholder-1/>In these cases, you should add extra characters to the strings. For instance, use <literal>"jumps[noun]"</literal> and <literal>"jumps[verb]"</literal> instead of just <literal>"jumps"</literal> and strip them again outside the <function>gettext</function> call. If you add extra characters you should also add a comment for the translators before the <function>gettext</function> call. Such comments will be shown in the <filename>.po</filename> files. For instance:In this example there are three event handlers that are called after <classname>Gtk::Window</classname>'s default event handler, one in the <classname>Gtk::Entry</classname>, one in the <classname>Gtk::Grid</classname> and one in the <classname>Gtk::Window</classname>.In this example there are three keyboard shortcuts: <keycap>Alt</keycap>+<keycap>1</keycap> selects the first radio button, <keycap>Alt</keycap>+<keycap>2</keycap> selects the second one, and the <keycap>Esc</keycap> key hides (closes) the window. The default event signal handler is overridden, as described in the <link linkend="sec-overriding-default-signal-handlers">Overriding default signal handlers</link> section in the appendix.In this example, we'll construct a small but fully functional <application>gtkmm</application> program and draw some lines into the window. The lines are drawn by creating a path and then stroking it. A path is created using the functions <methodname>Cairo::Context::move_to()</methodname> and <methodname>Cairo::Context::line_to()</methodname>. The function <methodname>move_to()</methodname> is similar to the act of lifting your pen off of the paper and placing it somewhere else -- no line is drawn between the point you were at and the point you moved to. To draw a line between two points, use the <methodname>line_to()</methodname> function.In this section of the tutorial, we'll cover the basic Cairo drawing model, describe each of the basic drawing elements in some detail (with examples), and then present a simple application that uses Cairo to draw a custom clock widget.In your <literal>src/Makefile.am</literal>, update your <literal>AM_CPPFLAGS</literal> to add the following preprocessor macro definition:In your callback, compare the vector of available targets with those that your application supports for pasting. You could enable or disable a Paste menu item, depending on whether pasting is currently possible. For instance:In your signal handler, you should examine the new value and then store it in the Model if that is appropriate for your application.Includes the other files.Independently sorted views of the same modelInfoBarInheritance can be used to derive new widgets. The derivation of new widgets in GTK+ C code is so complicated and error prone that almost no C coders do it. As a C++ developer you know that derivation is an essential Object Orientated technique.InitializationInstallationInstalling <application>gtkmm</application> with <application>jhbuild</application>Installing From SourceInstalling and Using the git version of <application>gtkmm</application>Instead of laboriously connecting signal handlers to signals, you can simply make a new class which inherits from a widget - say, a Button - and then override the default signal handler, such as Button::on_clicked(). This can be a lot simpler than hooking up signal handlers for everything.Intermediate typesInternationalization and LocalizationInternationalizing GNOME applicationsIntltool READMEIntroductionIt also takes an optional extra argument: <placeholder-1/>It follows the same form. The number 3 at the end of the type's name indicates that our signal handler will need three arguments. The first type in the type list is <type>void</type>, so that should be our signal handler's return type. The following three types are the argument types, in order. Our signal handler's prototype could look like this:It is common for binding modules to track the version number of the library they are wrapping. So, for instance, if the C library is at version 1.23.4, then the initial version of the binding module would be 1.23.0. However, avoid starting with an even minor version number as that usually indicates a stable release.It is good practice to put all modifications to the graphics state between <methodname>save()</methodname>/<methodname>restore()</methodname> function calls. For example, if you have a function that takes a <classname>Cairo::Context</classname> reference as an argument, you might implement it as follows:It supports pasting of 2 targets - both the custom one and a text one that creates an arbitrary text representation of the custom data.It uses <methodname>request_targets()</methodname> and the <literal>owner_change</literal> signal and disables the Paste button if it can't use anything on the clipboard.It's impossible to predict the amount of space necessary for text after it has been translated to other languages, or displayed in a different font. On Unix it is also impossible to anticipate the effects of every theme and window manager.It's possible that certain strings will be marked as <literal>fuzzy</literal> in the <filename>.po</filename> file. These translations will not substitute the original string. To make them appear, simply remove the <literal>fuzzy</literal> tag.Iterating over Model RowsIteratorsJonathonJongsmaJust call the non-const version of the same function, instead of generating almost duplicate code.Just like normal pointers, you can check whether a <classname>RefPtr</classname> points to anything.Keyboard EventsKeyboard Events - Event PropagationKeyboard Events - SimpleKingKjellLabelLabels are the main method of placing non-editable text in windows, for instance to place a title next to a <classname>Entry</classname> widget. You can specify the text in the constructor, or later with the <methodname>set_text()</methodname> or <methodname>set_markup()</methodname> methods.Lack of propertiesLaursenLess C++ code is required.Let's look at an example of overriding:Let's take a look at a slightly improved <literal>helloworld</literal>, showing what we've learnt.Let's take another look at a Signal's <literal>connect</literal> method:Like checkboxes, radio buttons also inherit from <classname>Gtk::ToggleButton</classname>, but these work in groups, and only one RadioButton in a group can be selected at any one time.Like the <classname>TreeView</classname>, you should probably put your <classname>TextView</classname> inside a <classname>ScrolledWindow</classname> to allow the user to see and move around the whole text area with scrollbars.Likewise, replace all instances of <varname>Joe Hacker</varname> by the name of the intended copyright holder, which is probably you. Do the same for the <varname>joe@example.com</varname> email address.Line ends can have different styles as well. The default style is for the line to start and stop exactly at the destination points of the line. This is called a Butt cap. The other options are Round (uses a round ending, with the center of the circle at the end point) or Square (uses a squared ending, with the center of the square at the end point). This setting is set using the function <methodname>Cairo::Context::set_line_cap()</methodname>.Line stylesListStoreListStore, for rowsLoading the .glade fileLooking up Items in the List of Recent FilesLots of people need to implement right-click context menus for <classname>TreeView</classname>'s so we will explain how to do that here to save you some time. Apart from one or two points, it's much the same as a normal context menu, as described in the <link linkend="sec-menus-popup">menus chapter</link>.Main MenuMain Menu exampleMakefile.am filesManaged WidgetsMany Cairo drawing functions have a <methodname>_preserve()</methodname> variant. Normally drawing functions such as <methodname>clip()</methodname>, <methodname>fill()</methodname>, or <methodname>stroke()</methodname> will clear the current path. If you use the <methodname>_preserve()</methodname> variant, the current path will be retained so that you can use the same path with the next drawing function.Many GUI toolkits require you to precisely place widgets in a window, using absolute positioning, often using a visual editor. This leads to several problems:Marking strings for translationMarkoMarksMaybe the user should not be able to select every item in your list or tree. For instance, in the gtk-demo, you can select a demo to see the source code, but it doesn't make any sense to select a demo category.Member instances can be used, simplifying memory management. All GTK+ C widgets are dealt with by use of pointers. As a C++ coder you know that pointers should be avoided where possible.Memory managementMenus and ToolbarsMessageDialogMethod macrosMethodsMicrosoft WindowsMiscellaneous WidgetsMixing C and C++ APIsModel ColumnsModelColumns()
{ add(m_col_id); add(m_col_name); }

  Gtk::TreeModelColumn&lt;int&gt; m_col_id;
  Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
};

ModelColumns m_columns;Modifying build filesModifying the List of Recent FilesMonitoring I/OMore information about what lies behind the internationalization and localization process is presented and demonstrated in: <placeholder-1/>More than one Model Column per View ColumnMost applications will have only one <classname>Window</classname>, or only one main window. These applications can use the <methodname>Gtk::Application::run(Gtk::Window&amp;)</methodname> overload. It shows the window and returns when the window has been hidden. This might happen when the user closes the window, or when your code decides to <methodname>hide()</methodname> the window. You can prevent the user from closing the window (for instance, if there are unsaved changes) by overriding <methodname>Gtk::Window::on_delete_event()</methodname>.Most custom widgets need their own <classname>Gdk::Window</classname> to draw on. Then you can call <methodname>Gtk::Widget::set_has_window(true)</methodname> in your constructor. (This is the default value.) If you do not call <methodname>set_has_window(false)</methodname>, you must override <methodname>on_realize()</methodname> and call <methodname>Gtk::Widget::set_realized()</methodname> and <methodname>Gtk::Widget::set_window()</methodname> from there.Most of our examples use this technique.Most of the chapters in this book deal with specific widgets. See the <link linkend="chapter-container-widgets">Container Widgets</link> section for more details about adding widgets to container widgets.Most of the useful member methods for this class are actually in the <classname>Gtk::FileChooser</classname> base class.Most packing uses boxes as in the above example. These are invisible containers into which we can pack our widgets. When packing widgets into a horizontal box, the objects are inserted horizontally from left to right or right to left depending on whether <methodname>pack_start()</methodname> or <methodname>pack_end()</methodname> is used. In a vertical box, widgets are packed from top to bottom or vice versa. You may use any combination of boxes inside or beside other boxes to create the desired effect.MoveMulti-Threaded ProgramMulti-threaded programsMultiple-item widgetsMultiple-item widgets inherit from <classname>Gtk::Container</classname>; just as with <classname>Gtk::Bin</classname>, you use the <methodname>add()</methodname> and <methodname>remove()</methodname> methods to add and remove contained widgets. Unlike <methodname>Gtk::Bin::remove()</methodname>, however, the <methodname>remove()</methodname> method for <classname>Gtk::Container</classname> takes an argument, specifiying which widget to remove.MurrayMurray CummingNext we call the Window's <methodname>set_border_width()</methodname> method. This sets the amount of space between the sides of the window and the widget it contains.Next we must adapt the various <filename>Makefile.am</filename> files: <placeholder-1/>Next you should create a <classname>UIManager</classname> and add the <classname>ActionGroup</classname> to the <classname>UIManager</classname> with <methodname>insert_action_group()</methodname> At this point is also a good idea to tell the parent window to respond to the specified keyboard shortcuts, by using <methodname>add_accel_group()</methodname>.Next, we use the Window's <methodname>add()</methodname> method to put <literal>m_button</literal> in the Window. (<methodname>add()</methodname> comes from <classname>Gtk::Container</classname>, which is described in the chapter on container widgets.) The <methodname>add()</methodname> method places the Widget in the Window, but it doesn't display the widget. <application>gtkmm</application> widgets are always invisible when you create them - to display them, you must call their <methodname>show()</methodname> method, which is what we do in the next line.Nicolai M. Josuttis, "The C++ Standard Library" - section 4.2Non-modal AboutDialogNormal C++ memory managementNote also that not all widgets receive all X events by default. To receive additional X events, you can use <methodname>Gtk::Widget::set_events()</methodname> before showing the widget, or <methodname>Gtk::Widget::add_events()</methodname> after showing the widget. However, some widgets must first be placed inside an <classname>EventBox</classname> widget. See the <link linkend="chapter-widgets-without-xwindows">Widgets Without X-Windows</link> chapter.Note that UTF-8 isn't compatible with 8-bit encodings like ISO-8859-1. For instance, German umlauts are not in the ASCII range and need more than 1 byte in the UTF-8 encoding. If your code contains 8-bit string literals, you have to convert them to UTF-8 (e.g. the Bavarian greeting "Grüß Gott" would be "Gr\xC3\xBC\xC3\x9F Gott").Note that files ending in <filename>.in</filename> will be used to generate files with the same name but without the <filename>.in</filename> suffix, by replacing some variables with actual values during the configure stage.Note that if you mention extra modules in addition to gtkmm-3.0, they should be separated by spaces, not commas.Note that in this case, we've expressed nearly everything in terms of the height and width of the window, including the width of the lines. Because of this, when you resize the window, everything scales with the window. Also note that there are three drawing sections in the function and each is wrapped with a <methodname>save()</methodname>/<methodname>restore()</methodname> pair so that we're back at a known state after each drawing.Note that most language teams only consist of 1-3 persons, so if your program contains a lot of strings, it might last a while before anyone has the time to look at it. Also, most translators do not want to waste their time (translating is a very time-consuming task) so if they do not assess your project as being really serious (in the sense that it is polished and being maintained) they may decide to spend their time on some other project.Note that the instance (such as m_Columns here) should usually not be static, because it often needs to be instantiated after glibmm has been instantiated.Note that we don't pass a pointer to <methodname>on_button_clicked()</methodname> directly to the signal's <methodname>connect()</methodname> method. Instead, we call <function>sigc::ptr_fun()</function>, and pass the result to <methodname>connect()</methodname>.Note that you can't just do <placeholder-1/> because the group is modified by <methodname>set_group()</methodname> and therefore non-const.Note that you must specify actions for sub menus as well as menu items.Note that, due to GTK+'s theming system, the appearance of these widgets will vary. In the case of checkboxes and radio buttons, they may vary considerably.Note, however, that the TreeView will provide iterators to the sorted model. You must convert them to iterators to the underlying child model in order to perform actions on that model. For instance:NotebookNotice that we provided <command>gmmproc</command> with the path to the .m4 convert files, the path to the .defs file, the name of a .hg file, the source directory, and the destination directory.Notice that we've used an initialiser statement to give the <literal>m_button</literal> object the label "Hello World".Notice, that after canceling an event, no other function will be called (even if it is from the same widget).Now let's look at our program's <function>main()</function> function. Here it is, without comments:Now let's look at the connection again:Now let's see what happens when an exception is thrown from a signal handler. Here's the source code. <placeholder-1/>Now let's take a look at the code that performs the actual drawing. The first section of <methodname>on_draw()</methodname> should be pretty familiar by now. This example again scales the coordinate system to be a unit square so that it's easier to draw the clock as a percentage of window size so that it will automatically scale when the window size is adjusted. Furthermore, the coordinate system is scaled over and down so that the (0, 0) coordinate is in the very center of the window.Now that there is a place to put your translations, you need to initialize <application>intltool</application> and <application>gettext</application>. Add the following code to your <literal>configure.ac</literal>, substituting 'programname' with the name of your program:Now that we understand the basics of the Cairo graphics library, we're almost ready to start drawing. We'll start with the simplest of drawing elements: the straight line. But first you need to know a little bit about Cairo's coordinate system. The origin of the Cairo coordinate system is located in the upper-left corner of the window with positive x values to the right and positive y values going down. <placeholder-1/>Now that we've covered the basics of drawing with Cairo, let's try to put it all together and create a simple application that actually does something. The following example uses Cairo to create a custom <classname>Clock</classname> widget. The clock has a second hand, a minute hand, and an hour hand, and updates itself every second.Now that you've seen signals and signal handlers in <application>gtkmm</application>, you might like to use the same technique to allow interaction between your own classes. That's actually very simple by using the <application>libsigc++</application> library directly.Now we edit the files to adapt them to our needs. You might prefer to use a multiple-file search-replace utility for this, such as <command>regexxer</command>. Note that nearly all of the files provided with the skeleton source tree contain placeholder text. Thus, the substitutions should be performed globally, and not be limited to the Automake and Autoconf files.OK, you say, that's nice, but what if I want to create my own handlers to respond when the user adjusts a <classname>Range</classname> widget or a <classname>SpinButton</classname>. To access the value of a <classname>Gtk::Adjustment</classname>, you can use the <methodname>get_value()</methodname> and <methodname>set_value()</methodname> methods:Objects and functions.Objects such as <classname>Gdk::Pixbuf</classname> can only be instantiated with a <methodname>create()</methodname> function. For instance, <placeholder-1/>Objects used via <classname>RefPtr</classname>: Pass the <classname>RefPtr</classname> as a const reference. For instance, <code>const Glib::RefPtr&lt;Gtk::FileFilter&gt;&amp; filter</code>.Occasionally you might want to make an <classname>Entry</classname> widget read-only. This can be done by passing <literal>false</literal> to the <methodname>set_editable()</methodname> method.Of course this means that you can store <classname>RefPtr</classname>s in standard containers, such as <classname>std::vector</classname> or <classname>std::list</classname>.Of course, a top-level container will not be added to another container. The programmer is responsible for destroying the top-level container using one of the traditional C++ techniques. For instance, your top-level Window might just be an instance in your <function>main()</function> function.Often when wrapping methods, it is desirable to store the return of the C function in what is called an output parameter. In this case, the C++ method returns <type>void</type> but an output parameter in which to store the value of the C function is included in the argument list of the C++ method. gmmproc allows such functionality, but appropriate initialization macros must be included to tell gmmproc how to initialize the C++ parameter from the return of the C function.OleOn Unix, the default preview handler uses an external viewer program. On Windows, the native preview dialog will be shown. If necessary you may override this behaviour and provide a custom preview dialog. See the example located in /examples/book/printing/advanced.Once you've built your software, you'll need to run your program within the jhbuild environment as well. To do this, you can again use the <command>jhbuild shell</command> command to start a new shell with the <application>jhbuild</application> environment set up. Alternatively, you can execute a one-off command in the <application>jhbuild</application> environment using the following command: <command>jhbuild run command-name</command>. In this case, the command will be run with the correct environment variables set, but will return to your previous environment after the program exits.Once you've configured <application>jhbuild</application> as described above, building <application>gtkmm</application> should be relatively straightforward. The first time you run <application>jhbuild</application>, you should run the following sequence of commands to ensure that <application>jhbuild</application> has the required tools and verify that it is set up correctly: <screen>$ jhbuild bootstrap
$ jhbuild sanitycheck</screen>One of the benefits of UTF-8 is that you don't need to use it unless you want to, so you don't need to retrofit all of your code at once. <classname>std::string</classname> will still work for 7-bit ASCII strings. But when you try to localize your application for languages like Chinese, for instance, you will start to see strange errors, and possible crashes. Then all you need to do is start using <classname>Glib::ustring</classname> instead.One of the major advantages of <application>gtkmm</application> is that it is crossplatform. <application>gtkmm</application> programs written on other platforms such as GNU/Linux can generally be transferred to Windows (and vice versa) with few modifications to the source.Openismus has more <ulink url="http://www.openismus.com/documents/linux/automake/automake.shtml">basic help with automake and autoconf</ulink>.Optional Parameter ProcessingOr you could specify the tag when first inserting the text: <placeholder-1/>Other macrosOther macros, such as <function>_WRAP_METHOD()</function> and <function>_WRAP_SIGNAL()</function> may only be used after a call to a <function>_CLASS_*</function> macro.Other than the signal's name (<literal>focus</literal>), two things are important to note here: the number following the word <classname>SignalProxy</classname> at the beginning (1, in this case), and the types in the list (<type>bool</type> and <type>Gtk::DirectionType</type>). The number indicates how many arguments the signal handler should have; the first type, <type>bool</type>, is the type that the signal handler should return; and the next type, <type>Gtk::DirectionType</type>, is the type of this signal's first, and only, argument. By looking at the reference documentation, you can see the names of the arguments too.Our examples all tend to have the same structure. They follow these steps for using a <classname>Widget</classname>:Output Parameter ProcessingOverriding default signal handlersOverviewPKG_CHECK_MODULES([MYAPP], [gtkmm-3.0 &gt;= 3.8.0])Pack the widget into a container using the appropriate call, e.g. <methodname>Gtk::Container::add()</methodname> or <methodname>pack_start()</methodname>.PackingPage setupPanedPanes divide a widget into two halves, separated by a moveable divider. The two halves (panes) can be oriented either horizontally (side by side) or vertically (one above the other).PangoParameter ReorderingParts of chapter on "Internationalization".Parts of the update from gtkmm 2 to gtkmm 3.PastePedroPer-child packing optionsPer-container packing optionsPermission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. You may obtain a copy of the GNU Free Documentation License from the Free Software Foundation by visiting their Web site or by writing to: Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.PitfallsPlease see <ulink url="http://live.gnome.org/gtkmm/MSWindows/BuildingGtkmm">http://live.gnome.org/gtkmm/MSWindows/BuildingGtkmm</ulink> for instructions on how to build gtkmm on Windws.PlugsPlugs and SocketsPlugs and Sockets ExamplePopup Context MenuPopup MenuPopup Menu examplePopup MenusPrebuilt PackagesPreparing your projectPretty thrilling, eh? Let's examine the code. First, the <classname>HelloWorld</classname> class:Preventing row selectionPreviewPrintOperationPrintingPrinting - SimpleProbably the most common way of creating <classname>Gdk::Pixbuf</classname>s is to use <methodname>Gdk::Pixbuf::create_from_file()</methodname>, which can read an image file, such as a png file into a pixbuf ready for rendering.Problems in the C API.Programming with <application>gtkmm</application> 3Progress bars are used to show the status of an ongoing operation. For instance, a <classname>ProgressBar</classname> can show how much of a task has been completed.ProgressBarPush-ButtonsPuts the generated code in #ifdef blocks.Puts the generated code in #ifdef blocks. Text about the deprecation can be specified as an optional parameter.Radio buttonsRadioButtonRange WidgetsRe. Overriding signal handlers: You can do this in the straight-C world of GTK+ too; that's what GTK's object system is for. But in GTK+, you have to go through some complicated procedures to get object-oriented features like inheritance and overloading. In C++, it's simple, since those features are supported in the language itself; you can let the compiler do the dirty work.Recent versions of <application>gtkmm</application> are packaged by nearly every major Linux distribution these days. So, if you use Linux, you can probably get started with <application>gtkmm</application> by installing the package from the official repository for your distribution. Distributions that include <application>gtkmm</application> in their repositories include Debian, Ubuntu, Red Hat, Fedora, Mandriva, Suse, and many others.RecentChooserRecentManagerRecently Used DocumentsRecommended TechniquesReferenceRemember that on a Unix or Linux operating system, you will probably need to be <literal>root</literal> to install software. The <command>su</command> or <command>sudo</command> command will allow you to enter the <literal>root</literal> password and have <literal>root</literal> status temporarily.Remember that these names are just the identifiers that we used when creating the actions. They are not the text that the user will see in the menus and toolbars. We provided those human-readable names when we created the actions.Remember that you are not instantiating a widget with <methodname>get_widget()</methodname>, you are just obtaining a pointer to one that already exists. You will always receive a pointer to the same instance when you call <methodname>get_widget()</methodname> on the same <classname>Gtk::Builder</classname>, with the same widget name. The widgets are instantiated during <methodname>Gtk::Builder::create_from_file()</methodname>.Rendering textReorderable rowsResourcesResponding to changesReusing C documentationRiederRow childrenSame strings, different semanticsScale WidgetsScrollbar WidgetsScrolled windows have <emphasis>scrollbar policies</emphasis> which determine whether the <classname>Scrollbar</classname>s will be displayed. The policies can be set with the <methodname>set_policy()</methodname> method. The policy may be one of <literal>Gtk::POLICY_AUTOMATIC</literal> or <literal>Gtk::POLICY_ALWAYS</literal>. <literal>Gtk::POLICY_AUTOMATIC</literal> will cause the scrolled window to display the scrollbar only if the contained widget is larger than the visible area. <literal>Gtk::POLICY_ALWAYS</literal> will cause the scrollbar to be displayed always.ScrolledWindowScrollingSecond, check for an error and connect to the <literal>status_changed</literal> signal. For instance: <placeholder-1/>Section "Build Structure" of chapter on "Wrapping C Libraries with gmmproc".Section on Gtk::Grid.See <link linkend="sec-printing-example-simple">an example</link> of exactly how this can be done.See the <link linkend="chapter-draganddrop">Drag and Drop</link> chapter for general advice about Drag and Drop with gtkmm.See the <link linkend="chapter-internationalization">Internationalization</link> section for information about providing the UTF-8 string literals.See the <link linkend="chapter-refptr">appendix</link> for detailed information about RefPtr.See the <link linkend="sec-progressbar">ProgressBar</link> section for another example that uses an <classname>Alignment</classname>.Selecting which C++ types should be used is also important when wrapping C API. Though it's usually obvious what C++ types should be used in the C++ method, here are some hints: <placeholder-1/>Set the attributes of the widget. If the widget has no default constructor, then you will need to initialize the widget in the initalizer list of your container class's constructor.Set the title of the tab via <methodname>PrintOperation::set_custom_tab_label()</methodname>, create a new widget and return it from the <literal>create_custom_widget</literal> signal handler. You'll probably want this to be a container widget, packed with some others.Setting a prefixSetting up jhbuildSetting valuesShared resourcesShown below is a simple example of how to use the <classname>RecentChooserDialog</classname> and the <classname>RecentAction</classname> classes in a program. This simple program has a menubar with a <guimenuitem>Recent Files Dialog</guimenuitem> menu item. When you select this menu item, a dialog pops up showing the list of recently used files.Signal Handler sequenceSignalsSignals and properties.Signals usually have function pointers in the GTK struct, with a corresponding enum value and a <function>g_signal_new()</function> in the .c file.SimpleSimple Entry ExampleSimple ExampleSimple RecentChooserDialog exampleSimple Text ExampleSimple UseSimple text copy-paste functionality is provided for free by widgets such as <classname>Gtk::Entry</classname> and <classname>Gtk::TextView</classname>, but you might need special code to deal with your own data formats. For instance, a drawing program would need special code to allow copy and paste within a view, or between documents.Since a <classname>Plug</classname> is just a special type of <classname>Gtk::Window</classname> class, you can add containers or widgets to it like you would to any other window.Since the Cairo graphics library was written with support for multiple output targets (the X window system, PNG images, OpenGL, etc), there is a distinction between user-space and device-space coordinates. The mapping between these two coordinate systems defaults to one-to-one so that integer values map roughly to pixels on the screen, but this setting can be adjusted if desired. Sometimes it may be useful to scale the coordinates so that the full width and height of a window both range from 0 to 1 (the 'unit square') or some other mapping that works for your application. This can be done with the <methodname>Cairo::Context::scale()</methodname> function.Since this is very similar to the methods above this explanation should be sufficient to understand what's going on. However, here's a little example:Single or multiple selectionSingle-item ContainersSo far we've told you to perform actions in response to button-presses and the like by handling signals. That's certainly a good way to do things, but it's not the only way.So that applications can react to changes, for instance when a user moves a scrollbar, <classname>Gtk::Adjustment</classname> has a <literal>value_changed</literal> signal. You can then use the <methodname>get_value()</methodname> method to discover the new value.So that the <classname>Entry</classname> can interact with the drop-down list of choices, you must specify which of your model columns is the text column, with <methodname>set_entry_text_column()</methodname>. For instance: <placeholder-1/>So you should either avoid this situation or use <ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1ustring.html"><function>Glib::ustring::compose()</function></ulink> which supports syntax such as: <placeholder-1/>So, for example, if you have a <classname>Scale</classname> widget, and you want to change the rotation of a picture whenever its value changes, you would create a signal handler like this:SocketsSome <application>gtkmm</application> widgets don't have associated X windows; they draw on their parents' windows. Because of this, they cannot receive events. Also, if they are incorrectly sized, they don't clip, so you can get messy overwriting etc. To receive events on one of these widgets, you can place it inside an <classname>EventBox</classname> widget and then call <methodname>Gtk::Widget::set_events()</methodname> on the EventBox before showing it.Some API related to gtkmm uses intermediate data containers, such as <classname>Glib::StringArrayHandle</classname>, instead of a specific Standard C++ container such as <classname>std::vector</classname> or <classname>std::list</classname>, though <application>gtkmm</application> itself now uses just <classname>std::vector</classname> since <application>gtkmm</application> 3.0.Some Widgets do not have an associated X-Window, so they therefore do not receive X events. This means that the signals described in the <link linkend="sec-xeventsignals">X event signals</link> section will not be emitted. If you want to capture events for these widgets you can use a special container called <classname>Gtk::EventBox</classname>, which is described in the <link linkend="sec-eventbox">EventBox</link> section.Some extra macros make this easier and consistent. Look in gtkmm's .m4 files for examples. For instance: <placeholder-1/>Some objects, such as <classname>Gdk::Pixbuf</classname>s and <classname>Pango::Font</classname>s, are obtained from a shared store. Therefore you cannot instantiate your own instances. These classes typically inherit from <classname>Glib::Object</classname>. Rather than requiring you to reference and unreference these objects, <application>gtkmm</application> uses the <classname>Glib::RefPtr&lt;&gt;</classname> smartpointer. Cairomm has its own smartpointer, <classname>Cairo::RefPtr&lt;&gt;</classname>.Some of the basic types that are used in C APIs have better alternatives in C++. For example, there's no need for a <type>gboolean</type> type since C++ has <type>bool</type>. The following list shows some commonly-used types in C APIs and what you might convert them to in a C++ wrapper library.Some thread safety rules on the use of <classname>Glib::Dispatcher</classname> still apply. As mentioned, a <classname>Glib::Dispatcher</classname> object must be constructed in the receiver thread (the thread in whose main loop it will execute its connected slots). By default this is the main program thread, although there is a <classname>Glib::Dispatcher</classname> constructor which can take the <classname>Glib::MainContext</classname> object of any thread which has a main loop. Only the receiver thread should call <methodname>connect()</methodname> on the <classname>Glib::Dispatcher</classname> object, or manipulate any related <classname>sigc::connection</classname> object, unless additional synchronization is employed. However, any worker thread can safely emit on the <classname>Glib::Dispatcher</classname> object without any locking once the receiver thread has connected the slots, provided that it is constructed before the worker thread is started (if it is constructed after the thread has started, additional synchronization will normally be required to ensure visibility).Sometimes two english strings are identical but have different meanings in different contexts, so they would probably not be identical when translated. Since the English strings are used as look-up keys, this causes problems.SortingSorting by clicking on columnsSource CodeSources and DestinationsSpecifies the destination directory for generated sources, and the name of the main .defs file that <command>gmmproc</command> should parse.Specifies the name of the slot parameter of the method, if it has one. This enables <command>gmmproc</command> to generate code to copy the slot and pass the copy on to the C function in its final <literal>gpointer user_data</literal> parameter. The <literal>slot_callback</literal> option must also be used to specify the name of the glue callback function to also pass on to the C function.Specifying CellRenderer detailsSpinButtonStart the <filename>plug</filename> program and send it to the background (or just use a different terminal).String literals should be typed in the source code in English, but surrounded by a macro. The <application>gettext</application> (or intltool) utility can then extract the marked strings for translation, and substitute the translated text at runtime.String literals should be typed in the source code in English, but they should be surrounded by a call to the <function>gettext()</function> function. These strings will be extracted for translation and the translations may be used at runtime instead of the original English strings.Subclass Widgets to better organize your code. You should probably subclass your main <classname>Window</classname> at least. Then you can make your child Widgets and signal handlers members of that class.Subclassing isn't always the best way to accomplish things. It is only useful when you want the widget to handle its own signal by itself. If you want some other class to handle the signal then you'll need to connect a separate handler. This is even more true if you want several objects to handle the same signal, or if you want one signal handler to respond to the same signal from different objects.TableTagTableTagsTags and FormattingTargetsTells <command>gmmproc</command> not to pass a copy of the slot to the C function, if the method has one. Instead the slot itself is passed. The slot parameter name and the glue callback function must have been specified with the <literal>slot_name</literal> and <literal>slot_callbback</literal> options respectively.Tells <command>gmmproc</command> to add initialization code for the interface.Tells <command>gmmproc</command> to add some typedefs, constructors, and standard methods to this class, as appropriate when wrapping a widget.Testing and adding translationsText is drawn via Pango Layouts. The easiest way to create a <classname>Pango::Layout</classname> is to use <methodname>Gtk::Widget::create_pango_layout()</methodname>. Once created, the layout can be manipulated in various ways, including changing the text, font, etc. Finally, the layout can be rendered using the <methodname>Pango::Layout::show_in_cairo_context()</methodname> method.Text rendering is done using Pango. The <classname>Pango::Layout</classname> object for printing should be created by calling the <methodname>PrintContext::create_pango_layout()</methodname> method. The <classname>PrintContext</classname> object also provides the page metrics, via <methodname>get_width()</methodname> and <methodname>get_height()</methodname>. The number of pages can be set with <methodname>PrintOperation::set_n_pages()</methodname>. To actually render the Pango text in <literal>on_draw_page</literal>, get a <classname>Cairo::Context</classname> with <methodname>PrintContext::get_cairo_context()</methodname> and show the <classname>Pango::LayoutLine</classname>s that appear within the requested page number.TextViewThat will create a file named <filename>programname.pot</filename>. Now copy that file to <filename>languagecode.po</filename>, such as <filename>de.po</filename> or <filename>hu.po</filename>. Also add that language code to <literal>LINGUAS</literal>. The <filename>.po</filename> file contains a header and a list of English strings, with space for the translated strings to be entered. Make sure you set the encoding of the <filename>.po</filename> file (specified in the header, but also as content) to <literal>UTF-8</literal>.The "changed" signalThe 'Print to file' option is available in the print dialog, without the need for extra implementation. However, it is sometimes useful to generate a pdf file directly from code. For instance, <placeholder-1/>The .h and .cc files will be generated from the .hg and .ccg files by processing them with <command>gmmproc</command> like so, though this happens automatically when using the above build structure: <placeholder-1/>The .hg and .ccg filesThe .hg and .ccg source files are very much like .h and .cc C++ source files, but they contain extra macros, such as <function>_CLASS_GOBJECT()</function> and <function>_WRAP_METHOD()</function>, from which <command>gmmproc</command> generates appropriate C++ source code, usually at the same position in the header. Any additional C++ source code will be copied verbatim into the corresponding .h or .cc file.The <application>GNU gettext</application> package allows you to mark strings in source code, extract those strings for translation, and use the translated strings in your application.The <application>gtkmm</application> module is defined in the <filename>gnome-suites-core-deps-3.x.modules</filename> moduleset, so edit your <filename>.jhbuildrc</filename> file and set your moduleset setting to the latest version e.g. like so: <placeholder-1/>The <classname>AboutDialog</classname> offers a simple way to display information about a program, like its logo, name, copyright, website and license.The <classname>Alignment</classname> widget allows you to place a widget at a position and size relative to the size of the <classname>Alignment</classname> widget itself. For instance, it might be used to center a widget.The <classname>AspectFrame</classname> widget looks like a <classname>Frame</classname> widget, but it also enforces the <emphasis>aspect ratio</emphasis> (the ratio of the width to the height) of the child widget, adding extra space if necessary. For instance, this would allow you to display a photograph without allowing the user to distort it horizontally or vertically while resizing.The <classname>ColorChooserDialog</classname> allows the user to choose a color. The <classname>ColorButton</classname> opens a color selection dialog when it is clicked.The <classname>ComboBox</classname> widget offers a list (or tree) of choices in a dropdown menu. If appropriate, it can show extra information about each item, such as text, a picture, a checkbox, or a progress bar. The <classname>ComboBox</classname> widget usually restricts the user to the available choices, but it can optionally have an <classname>Entry</classname>, allowing the user to enter arbitrary text if none of the available choices are suitable.The <classname>DrawingArea</classname> widget is a blank window that gives you the freedom to create any graphic you desire. Along with that freedom comes the responsibility to handle draw signals on the widget. When a widget is first shown, or when it is covered and then uncovered again it needs to redraw itself. Most widgets have code to do this, but the DrawingArea does not, allowing you to write your own draw signal handler to determine how the contents of the widget will be drawn. This is most often done by overriding the virtual <methodname>on_draw()</methodname> member function.The <classname>EntryCompletion</classname> may use a <classname>TreeModel</classname> containing possible entries, specified with <methodname>set_model()</methodname>. You should then call <methodname>set_text_column()</methodname> to specify which of your model columns should be used to match possible text entries.The <classname>FileChooserDialog</classname> is suitable for use with "Open" or "Save" menu items.The <classname>FontChooserDialog</classname> allows the user to choose a font. The <classname>FontButton</classname> opens a font chooser dialog when it is clicked.The <classname>Gdk::Pixbuf</classname> can be rendered by setting it as the source pattern of the Cairo context with <methodname>Gdk::Cairo::set_source_pixbuf()</methodname>. Then draw the image with either <methodname>Cairo::Context::paint()</methodname> (to draw the whole image), or <methodname>Cairo::Context::rectangle()</methodname> and <methodname>Cairo::Context::fill()</methodname> (to fill the specified rectangle). <methodname>set_source_pixbuf()</methodname> is not a member of <classname>Cairo::Context</classname>. It takes a <classname>Cairo::Context</classname> as its first parameter.The <classname>Gtk::Button</classname> widget has the following signals, but most of the time you will just handle the <literal>clicked</literal> signal:The <classname>Gtk::TreeView</classname> widget can contain lists or trees of data, in columns.The <classname>ListStore</classname> contains simple rows of data, and each row has no children.The <classname>PrintOperation</classname> class has a method called <methodname>set_default_page_setup()</methodname> which selects the default paper size, orientation and margins. To show a page setup dialog from your application, use the <methodname>Gtk::run_page_setup_dialog()</methodname> method, which returns a <classname>Gtk::PageSetup</classname> object with the chosen settings. Use this object to update a <classname>PrintOperation</classname> and to access the selected <classname>Gtk::PaperSize</classname>, <literal>Gtk::PageOrientation</literal> and printer-specific margins.The <classname>SpinButton</classname> can create a default <classname>Adjustment</classname>, which you can access via the <methodname>get_adjustment()</methodname> method, or you can specify an existing <classname>Adjustment</classname> in the constructor.The <classname>Tag</classname> class has many other properties.The <classname>TextView</classname> creates its own default <classname>TextBuffer</classname>, which you can access via the <methodname>get_buffer()</methodname> method.The <classname>TextView</classname> widget can be used to display and edit large amounts of formatted text. Like the <classname>TreeView</classname>, it has a model/view design. In this case the <classname>TextBuffer</classname> is the model.The <classname>ToolPalette</classname>'s items might be dragged or simply activated. For instance, the user might drag objects to a canvas to create new items there. Or the user might click an item to activate a certain brush size in a drawing application.The <classname>TreeModelColumnRecord</classname> class is used to keep track of the columns and their data types. You add <classname>TreeModelColumn</classname> instances to the <classname>ColumnRecord</classname> and then use those <classname>TreeModelColumns</classname> when getting and setting the data in model rows. You will probably find it convenient to derive a new <classname>TreeModelColumnRecord</classname> which has your <classname>TreeModelColumn</classname> instances as member data.The <classname>TreeStore</classname> contains rows of data, and each row may have child rows.The <classname>TreeView</classname> already allows you to show the same <classname>TreeModel</classname> in two <classname>TreeView</classname> widgets. If you need one of these TreeViews to sort the model differently than the other then you should use a <classname>TreeModelSort</classname> instead of just, for instance, <methodname>Gtk::TreeViewModel::set_sort_column()</methodname>. <classname>TreeModelSort</classname> is a model that contains another model, presenting a sorted version of that model. For instance, you might add a sorted version of a model to a <classname>TreeView</classname> like so:The <classname>Widget</classname> class has some special signals which correspond to the underlying X-Windows events. These are suffixed by <literal>_event</literal>; for instance, <methodname>Widget::signal_button_press_event()</methodname>.The <emphasis>update policy</emphasis> of a <classname>Range</classname> widget defines at what points during user interaction it will change the <literal>value</literal> field of its <classname>Gtk::Adjustment</classname> and emit the <literal>value_changed</literal> signal. The update policies, set with the <methodname>set_update_policy()</methodname> method, are: <placeholder-1/>The <filename>.defs</filename> files are text files, in a lisp format, that describe the API of a C library, including its <placeholder-1/>The <filename>configure</filename> script will check to make sure all of the required dependencies are already installed. If you are missing any dependencies, it will exit and display an error.The <function>AC_CONFIG_FILES()</function> block must mention the correct directory names, as described above.The <function>AC_CONFIG_SRCDIR()</function> line must mention a file in our source tree. We can edit this later if we don't yet know the names of any of the files that we will create.The <function>AC_SUBST([SOMETHINGMM_MODULES], ['...'])</function> line may need to be modified to check for the correct dependencies.The <function>_CTOR_DEFAULT()</function> and <function>_WRAP_CTOR()</function> macros add constructors, wrapping the specified <function>*_new()</function> C functions. These macros assume that the C object has properties with the same names as the function parameters, as is usually the case, so that it can supply the parameters directly to a <function>g_object_new()</function> call. These constructors never actually call the <function>*_new()</function> C functions, because gtkmm must actually instantiate derived GTypes, and the <function>*_new()</function> C functions are meant only as convenience functions for C programmers.The <link linkend="chapter-draganddrop">Drag and Drop</link> API uses the same mechanism. You should probably use the same data targets and formats for both Clipboard and Drag and Drop operations.The <literal>const ... &amp;</literal> around both is just for efficiency, like using <classname>const std::string&amp;</classname> instead of <classname>std::string</classname> for a method parameter to avoid unnecessary copying.The <literal>ideal</literal> example below can supply more than one clipboard target.The <methodname>PrintOperation::run()</methodname> method starts the print loop, during which various signals are emitted: <placeholder-1/>The <methodname>get_request_mode_vfunc()</methodname>, <methodname>get_preferred_width_vfunc()</methodname>, <methodname>get_preferred_height_vfunc()</methodname>, <methodname>get_preferred_width_for_height_vfunc()</methodname>, <methodname>get_preferred_height_for_width_vfunc()</methodname>, and <methodname>on_size_allocate()</methodname> virtual methods control the layout of the child widgets. For instance, if your container has 2 child widgets, with one below the other, your <methodname>get_request_mode_vfunc()</methodname> might request height-for-width layout. Then your <methodname>get_preferred_width_vfunc()</methodname> might report the maximum of the widths of the child widgets, and <methodname>get_preferred_height_for_width_vfunc()</methodname> might report the sum of their heights. If you want padding between the child widgets then you would add that to the width and height too. Your widget's container will use this result to ensure that your widget gets enough space, and not less. By examining each widget's parent, and its parent, this logic will eventually decide the size of the top-level window.The <methodname>pack_start()</methodname> and <methodname>pack_end()</methodname> methods place widgets inside these containers. The <methodname>pack_start()</methodname> method will start at the top and work its way down in a <classname>Box</classname> with vertical orientation, or pack left to right in a <classname>Box</classname> with horizontal orientation. <methodname>pack_end()</methodname> will do the opposite, packing from bottom to top or from right to left. Using these methods allows us to right justify or left justify our widgets. We will use <methodname>pack_start()</methodname> in most of our examples.The <methodname>run()</methodname> method returns an <literal>int</literal>. This may be a value from the <literal>Gtk::ResponseType</literal> if the user closed the dialog by clicking a standard button, or it could be the custom response value that you specified when using <methodname>add_button()</methodname>.The <methodname>spin()</methodname> method 'spins' the <classname>SpinButton</classname>, as if its increment or decrement button had been clicked. You need to specify a <classname>Gtk::SpinType</classname> to specify the direction or new position.The <parameter>options</parameter> argument can take one of these three options: <placeholder-1/>The <parameter>padding</parameter> argument specifies the width of an extra border area to leave around the packed widget.The BufferThe C function (e.g. <function>get_request_mode</function>) is described more fully in the <filename>*_vfuncs.defs</filename> file, and the <filename>convert*.m4</filename> files contain the necessary conversion from the C++ parameter type to the C parameter type.The C function (e.g. <function>gtk_entry_set_text</function>) is described more fully in the .defs file, and the <filename>convert*.m4</filename> files contain the necessary conversion from the C++ parameter type to the C parameter type. This macro also generates doxygen documentation comments based on the <filename>*_docs.xml</filename> and <filename>*_docs_override.xml</filename> files.The Cairo Drawing ModelThe Cairo coordinate system, in the <literal>draw_page</literal> handler, is automatically rotated to the current page orientation. It is normally within the printer margins, but you can change that via the <methodname>PrintOperation::set_use_full_page()</methodname> method. The default measurement unit is device pixels. To select other units, use the <methodname>PrintOperation::set_unit()</methodname> method.The ClipboardThe Drawing Area WidgetThe ModelThe RefPtr smartpointerThe SelectionThe TreeView widgetThe UI layout for a popup menu should use the <literal>popup</literal> node. For instance:The ViewThe View is the actual widget (<classname>Gtk::TreeView</classname>) that displays the model (<classname>Gtk::TreeModel</classname>) data and allows the user to interact with it. The View can show all of the model's columns, or just some, and it can show them in various ways.The adjustable widgets can be roughly divided into those which use and require specific units for these values, and those which treat them as arbitrary numbers.The arguments to <methodname>Action::create()</methodname> specify the action's name and how it will appear in menus and toolbars.The basic concept of drawing in Cairo involves defining 'invisible' paths and then stroking or filling them to make them visible.The build structureThe chosen itemThe class macro declares the class itself and its relationship with the underlying C type. It generates some internal constructors, the member <varname>gobject_</varname>, typedefs, the <function>gobj()</function> accessors, type registration, and the <function>Glib::wrap()</function> method, among other things.The clear callback allows you to free the memory used by your stored data when the clipboard replaces its data with something else.The command line options passed to the C preprocessor.The command line options passed to the C++ compiler.The communication between a <classname>Socket</classname> and a <classname>Plug</classname> follows the XEmbed protocol. This protocol has also been implemented in other toolkits (e.g. Qt), which allows the same level of integration when embedding a Qt widget in GTK+ or vice versa.The compiler will complain if you use an inappropriate type. For instance, this would generate a compiler error:The connect*_once() variants, <methodname>Glib::SignalIdle::connect_once()</methodname>, <methodname>Glib::SignalTimeout::connect_once()</methodname>, <methodname>Glib::SignalTimeout::connect_seconds_once()</methodname>, are thread-safe for any case where the slot is not created by a call to <function>sigc::mem_fun()</function> which represents a method of a class deriving from <classname>sigc::trackable</classname>. This is similar to <methodname>Glib::Threads::Thread::create()</methodname> as mentioned in point 4.The constraintsThe constructor for <classname>ExampleWindow</classname> creates the menu using <classname>UIManager</classname> (see <xref linkend="chapter-menus-and-toolbars"/> for more information). It then adds the menu and the toolbar to the window.The constructor for <classname>Gtk::EventBox</classname> is:The current state of a <classname>Cairo::Context</classname> can be saved to an internal stack of saved states and later be restored to the state it was in when you saved it. To do this, use the <methodname>save()</methodname> method and the <methodname>restore()</methodname> method. This can be useful if you need to temporarily change the line width and color (or any other graphics setting) in order to draw something and then return to the previous settings. In this situation, you could call <methodname>Cairo::Context::save()</methodname>, change the graphics settings, draw the lines, and then call <methodname>Cairo::Context::restore()</methodname> to restore the original graphics state. Multiple calls to <methodname>save()</methodname> and <methodname>restore()</methodname> can be nested; each call to <methodname>restore()</methodname> restores the state from the matching paired <methodname>save()</methodname>. <placeholder-1/>The drag and drop signals provide a DragContext, which contains some information about the drag and drop operation and can be used to influence the process. For instance, you can discover the source widget, or change the drag and drop icon, by using the <methodname>set_icon()</methodname> methods. More importantly, you should call the <methodname>drag_finish()</methodname> method from your <literal>drag_data_received</literal> signal handler to indicate whether the drop was successful.The entryThe event is delivered first to the widget the event occurred in. If all signal handlers in that widget return <literal>false</literal> (indicating that the event has not been handled), then the signal will be propagated to the parent widget and emitted there. This continues all the way up to the top-level widget if no one handles the event.The event will propagate until it reaches the top-level widget, or until you stop the propagation by returning <literal>true</literal> from an event handler.The example in examples/book/printing/advanced demonstrates this.The extra typedef allows the struct to be used in a header without including its full definition, simply by predeclaring it, by repeating that typedef. This means that you don't have to include the C library's header in your C++ header, thus keeping it out of your public API. <command>gmmproc</command> assumes that this technique was used, so you will see compiler errors if that is not the case.The first 6 methods in the previous table are also overridden in custom containers. They are briefly described in the <link linkend="sec-custom-containers">Custom Containers</link> section.The first argument is a <classname>slot</classname> you wish to have called when the timeout occurs. The second argument is the number of milliseconds between calls to that method. You receive a <classname>sigc::connection</classname> object that can be used to deactivate the connection using its <methodname>disconnect()</methodname> method:The first argument is the widget you're packing. In our example these are all <classname>Button</classname>s.The first call to <methodname>connect()</methodname> is just like the one we saw last time; nothing new here.The first line of output is from <filename>plug</filename>, after it has been notified that it has been embedded inside of a <classname>Socket</classname>. The second line was emitted by <filename>socket</filename> in response to its <methodname>plug_added</methodname> signal. If everything was done as described above, the <filename>socket</filename> window should look roughly like the following:The following example demonstrates both uses of an <classname>EventBox</classname> - a label is created that is clipped to a small box, and set up so that a mouse-click on the label causes the program to exit. Resizing the window reveals varying amounts of the label.The following example demonstrates how to print some input from a user interface. It shows how to implement <literal>on_begin_print</literal> and <literal>on_draw_page</literal>, as well as how to track print status and update the print settings.The following example demonstrates the use of <classname>RadioButton</classname>s:The following example program requires a command-line option. The source code shows two ways of handling command-line options in combination with <classname>Gtk::Application</classname>.The following example shows how to set up a Cairo context with a foreground color of red and a width of 2. Any drawing functions that use this context will use these settings.The following is a simple example of using sockets and plugs. The method of communication between processes is deliberately kept very simple: The <classname>Plug</classname> writes its ID out to a text file named <filename>plug.id</filename> and the process with the socket reads the ID from this file. In a real program, you may want to use a more sophisticated method of inter-process communication.The following program uses a <classname>Gtk::AspectFrame</classname> to present a drawing area whose aspect ratio will always be 2:1, no matter how the user resizes the top-level window.The function <methodname>Cairo::Context::arc_negative()</methodname> is exactly the same as <methodname>Cairo::Context::arc()</methodname> but the angles go the opposite direction.The functions <methodname>move_item()</methodname>, <methodname>remove_item()</methodname> and <methodname>purge_items()</methodname> have no effect on the actual files that are referred to by the URIs, they only modify the list of recent files.The group which treats the values as arbitrary numbers includes the <classname>Range</classname> widgets (<classname>Scrollbar</classname> and <classname>Scale</classname>), the <classname>ScaleButton</classname> widget, and the <classname>SpinButton</classname> widget. These widgets are typically "adjusted" directly by the user with the mouse or keyboard. They will treat the <parameter>lower</parameter> and <parameter>upper</parameter> values of an adjustment as a range within which the user can manipulate the adjustment's <parameter>value</parameter>. By default, they will only modify the <parameter>value</parameter> of an adjustment.The implementation of the <function>wrap_init()</function> method in <filename>wrap_init.cc</filename> is generated by <filename>generate_wrap_init.pl</filename>, but the declaration in <filename>wrap_init.h</filename> is hand-coded, so you will need to adjust <filename>wrap_init.h</filename> so that the <function>wrap_init()</function> function appears in the correct C++ namespace.The label text can be justified using the <methodname>set_justify()</methodname> method. The widget is also capable of word-wrapping, which can be activated with <methodname>set_line_wrap()</methodname>.The last line shows the window and enters the <application>gtkmm</application> main processing loop, which will finish when the window is closed. Your <function>main()</function> function will then return with an appropriate success or error code.The line join style is set using the function <methodname>Cairo::Context::set_line_join()</methodname>.The list is provided via a <classname>TreeModel</classname>, and columns from this model are added to the ComboBox's view with the <methodname>ComboBox::pack_start()</methodname> method. This provides flexibility and compile-time type-safety, but the <classname>ComboBoxText</classname> class provides a simpler text-based specialization in case that flexibility is not required.The macros are explained in more detail in the following sections.The macros in this example do the following: <placeholder-1/>The macros that you use in the .hg and .ccg files often need to know how to convert a C++ type to a C type, or vice-versa. gmmproc takes this information from an .m4 file in your <literal>tools/m4/</literal> directory. This allows it to call a C function in the implementation of your C++ method, passing the appropriate parameters to that C functon. For instance, this tells gmmproc how to convert a GtkTreeView pointer to a Gtk::TreeView pointer: <placeholder-1/>The main activity in the internationalization process is finding strings seen by users and marking them for translation. You do not need to do it all at once - if you set up the necessary project infrastructure correctly then your application will work normally regardless of how many strings you've covered.The maximum age of items in the recently used files list can be set with <methodname>Gtk::Settings::property_gtk_recent_files_max_age()</methodname>. Default value: 30 days.The modelThe model for a ComboBox can be defined and filled exactly as for a <classname>TreeView</classname>. For instance, you might derive a ComboBox class with one integer and one text column, like so:The name of the library, such as libsomethingmm.The names of the <application>gtkmm</application> packages vary from distribution to distribution (e.g. <application>libgtkmm-3.0-dev</application> on Debian and Ubuntu or <application>gtkmm30-devel</application> on Red Hat Fedora), so check with your distribution's package management program for the correct package name and install it like you would any other package.The native GTK+ print dialog has a preview button, but you may also start a preview directly from an application: <placeholder-1/>The next is more interesting. <function>sigc::mem_fun()</function> is called with two arguments. The first argument is <parameter>some_object</parameter>, which is the object that our new slot will be pointing at. The second argument is a pointer to one of its methods. This particular version of <function>sigc::mem_fun()</function> creates a slot which will, when "called", call the pointed-to method of the specified object, in this case <methodname>some_object.on_button_clicked()</methodname>.The next statement: <placeholder-1/> creates a <classname>Gtk::Application</classname> object, stored in a <classname>RefPtr</classname> smartpointer. This is needed in all <application>gtkmm</application> applications. The <methodname>create()</methodname> method for this object initializes <application>gtkmm</application>, and checks the arguments passed to your application on the command line, looking for standard options such as <literal>--display</literal>. It takes these from the argument list, leaving anything it does not recognize for your application to parse or ignore. This ensures that all <application>gtkmm</application> applications accept the same set of standard arguments.The next two lines of code create a window and set its default (initial) size:The number of decimal places can be altered using the <methodname>set_digits()</methodname> method.The only difference between this example and the straight line example is in the <methodname>on_draw()</methodname> function, but there are a few new concepts and functions introduced here, so let's examine them briefly.The orientation of a <classname>Gtk::Scrollbar</classname> can be either horizontal or vertical.The other group includes the <classname>Viewport</classname> widget and the <classname>ScrolledWindow</classname> widget. All of these widgets use pixel values for their adjustments. These are also typically adjusted indirectly using scrollbars. While all widgets which use adjustments can either create their own adjustments or use ones you supply, you'll generally want to let this particular category of widgets create its own adjustments.The package names will not change when new API/ABI-compatible versions of <application>gtkmm</application> are released. Otherwise they would not be API/ABI-compatible. So don't be surprised, for instance, to find <application>gtkmm</application> 3.8 supplied by Debian's <application>libgtkmm-3.0-dev</application> package.The primary disadvantage of using class scope widgets is revealing the class implementation rather than the class interface in the class header.The primary object is <classname>Gtk::PrintOperation</classname>, allocated for each print operation. To handle page drawing connect to its signals, or inherit from it and override the default virtual signal handlers. <classname>PrintOperation</classname> automatically handles all the settings affecting the print loop.The process of writing source code that allows for translation is called <literal>internationalization</literal>, often abbreviated to <literal>i18n</literal>. The <literal>Localization</literal> process, sometimes abbreviated as <literal>l10n</literal>, provides translated text for other languages, based on that source code.The progress bar can also display a configurable text string within its trough, using the <methodname>set_text()</methodname> method.The purpose of this example is to show the steps the event takes when it is emitted.The return value is a <classname>sigc::connection</classname> that may be used to stop monitoring this file descriptor using its <methodname>disconnect()</methodname> method. The <parameter>slot</parameter> signal handler should be declared as follows:The rulesThe same principles apply for signals which have more arguments. Here's one with three (taken from <filename>&lt;gtkmm/textbuffer.h&gt;</filename>):The second way to set up radio buttons is to make a group first, and then add radio buttons to it. Here's an example:The section for drawing an arc introduces one new function, <methodname>close_path()</methodname>. This function will in effect draw a straight line from the current point back to the first point in the path. There is a significant difference between calling <methodname>close_path()</methodname> and manually drawing a line back to the starting point, however. If you use <methodname>close_path()</methodname>, the lines will be nicely joined together. If you use <methodname>line_to()</methodname> instead, the lines will end at the same point, but Cairo won't do any special joining.The selected rowsThe signal handler is <methodname>on_button_clicked()</methodname>.The single-item container widgets derive from <classname>Gtk::Bin</classname>, which provides the <methodname>add()</methodname> and <methodname>remove()</methodname> methods for the child widget. Note that <classname>Gtk::Button</classname> and <classname>Gtk::Window</classname> are technically single-item containers, but we have discussed them already elsewhere.The slots connected to <classname>sigc::signal</classname> objects execute in the thread which calls <methodname>emit()</methodname> or <methodname>operator()()</methodname> on the signal. <classname>Glib::Dispatcher</classname> does not behave this way: instead its connected slots execute in the thread in which the <classname>Glib::Dispatcher</classname> object was constructed (which must have a glib main loop). If a <classname>Glib::Dispatcher</classname> object is constructed in the main GUI thread (which will therefore be the receiver thread), any worker thread can emit on it and have the connected slots safely execute <application>gtkmm</application> functions.The source widget will emit these signals, in this order: <placeholder-1/>The standard tree models (<classname>TreeStore</classname> and <classname>ListStore</classname>) derive from <classname>TreeSortable</classname>, so they offer sorting functionality. For instance, call <methodname>set_sort_column()</methodname>, to sort the model by the specified column. Or supply a callback function to <methodname>set_sort_func()</methodname> to implement a more complicated sorting algorithm.The text columnThe trick is to position in the middle of the pixel where you want the line to be drawn, and thus guaranteeing you get the desired results. See <ulink url="http://cairographics.org/FAQ/#sharp_lines">Cairo FAQ</ulink>.The use of the <literal>const</literal> keyword in C++ is not always clear. You might not realise that <type>const Something*</type> declares a pointer to a <type>const Something</type>. The pointer can be changed, but not the <type>Something</type> that it points to.The value can have an adjustable number of decimal places, and the step size is configurable. <classname>SpinButton</classname>s have an 'auto-repeat' feature as well: holding down the increment or decrement button can optionally cause the value to change more quickly the longer the button is held down.The value displayed by a scale widget is rounded to one decimal point by default, as is the <literal>value</literal> field in its <classname>Gtk::Adjustment</classname>. You can change this with the <methodname>set_digits()</methodname> method.The virtual <methodname>on_draw()</methodname> method provides a Cairo context that you shall use for drawing in the <classname>Gtk::DrawingArea</classname> widget. It is not necessary to save and restore this Cairo context in <methodname>on_draw()</methodname>.The way it works is that you upload your source code to a git repository where translators can access it, then contact the gnome-i18n mailing list and ask to have your program added to the <ulink url="http://l10n.gnome.org/module/">list of modules to translate</ulink>.The way that <classname>Sockets</classname> and <classname>Plugs</classname> work together is through their window ids. Both a <classname>Socket</classname> and a <classname>Plug</classname> have IDs that can be retrieved with their <methodname>get_id()</methodname> member functions. The use of these IDs will be explained below in <xref linkend="sec-connecting-plugs-sockets"/>.The widgets don't rearrange themselves when the window is resized. Some widgets are hidden when the window is made smaller, and lots of useless space appears when the window is made larger.The width of the label will be adjusted automatically. You can produce multi-line labels by putting line breaks ("\n") in the label string.The window ID is: 69206019Then edit the <filename>.cc</filename> file to specify the correct types. For instance, your <function>main()</function> function might look like this: <placeholder-1/>Then start the <filename>socket</filename> program:Then you make sure you update the file <filename>POTFILES.in</filename> in the <filename>po/</filename> subdirectory (<command>intltool-update -M</command> can help with this) so that the translators always access updated <filename>myprogram.pot</filename> files, and simply freeze the strings at least a couple of days before you make a new release, announcing it on gnome-i18n. Depending on the number of strings your program contains and how popular it is, the translations will then start to tick in as <filename>languagename.po</filename> files.Then, to add a widget at that position, use <methodname>Gtk::TextView::add_child_at_anchor()</methodname>:Then, you can define the actual visible layout of the menus and toolbars, and add the UI layout to the <classname>UIManager</classname>. This "ui string" uses an XML format, in which you should mention the names of the actions that you have already created. For instance:There are a couple of things to note about this example code. Again, the only real difference between this example and the previous ones is the <methodname>on_draw()</methodname> function, so we'll limit our focus to that function. In addition, the first part of the function is nearly identical to the previous examples, so we'll skip that portion.There are a few common mistakes that you would discover eventually yourself. But this section might help you to avoid them.There are a number of graphics state variables that can be set for a Cairo context. The most common context attributes are color (using <methodname>set_source_rgb()</methodname> or <methodname>set_source_rgba()</methodname> for translucent colors), line width (using <methodname>set_line_width()</methodname>), line dash pattern (using <methodname>set_dash()</methodname>), line cap style (using <methodname>set_line_cap()</methodname>), and line join style (using <methodname>set_line_join()</methodname>), and font styles (using <methodname>set_font_size()</methodname>, <methodname>set_font_face()</methodname> and others). There are many other settings as well, such as transformation matrices, fill rules, whether to perform antialiasing, and others. For further information, see the <ulink url="http://www.cairographics.org/cairomm/">cairomm</ulink> API documentation.There are basically five different styles, as shown in this picture:There are other things you can customize as well, including creating dashed lines and other things. For more information, see the Cairo API documentation.There are several derived <classname>Dialog</classname> classes which you might find useful. <classname>Gtk::MessageDialog</classname> is used for most simple notifications. But at other times you might need to derive your own dialog class to provide more complex functionality.There are several options governing how widgets are to be packed, and this can be confusing at first. If you have difficulties then it is sometimes a good idea to play with the <application>glade</application> GUI designer to see what is possible. You might even decide to use the <application>Gtk::Builder</application> API to load your GUI at runtime.There are several other containers, which we will also discuss.There are some optional extra arguments: <placeholder-1/>There are specific APIs for Menus and toolbars, but you should usually deal with them together, using the <classname>UIManager</classname> to define <classname>Action</classname>s which you can then arrange in menus and toolbars. In this way you can handle activation of the action instead of responding to the menu and toolbar items separately. And you can enable or disable both the menu and toolbar item via the action.There are two basic strategies that can be used: <placeholder-1/>There are two built-in <classname>Mark</classname>s - <literal>insert</literal> and <literal>selection_bound</literal>, which you can access with <classname>TextBuffer</classname>'s <methodname>get_insert()</methodname> and <methodname>get_selection_bound()</methodname> methods.There are two ways to create a Button. You can specify a label string in the <classname>Gtk::Button</classname> constructor, or set it later with <methodname>set_label()</methodname>.There are two ways to set up a group of radio buttons. The first way is to create the buttons, and set up their groups afterwards. Only the first two constructors are used. In the following example, we make a new window class called <classname>RadioButtons</classname>, and then put three radio buttons in it:There is a method for drawing from a <classname>Gdk::Pixbuf</classname> to a <classname>Cairo::Context</classname>. A <classname>Gdk::Pixbuf</classname> buffer is a useful wrapper around a collection of pixels, which can be read from files, and manipulated in various ways.There is a more complex example in examples/others/dnd.There is one optional extra argument: <placeholder-1/>There may be times when you need to modify the list of recent files. For instance, if a file is moved or renamed, you may need to update the file's location in the recent files list so that it doesn't point to an incorrect location. You can update an item's location by using <methodname>move_item()</methodname>.There's rather a lot to think about in this (non-functional) code. First let's identify the parties involved:Therefore, the <classname>RefPtr</classname> equivalent of <type>Something*</type> for a method parameter is <type>const Glib::RefPtr&lt;Something&gt;&amp;</type>, and the equivalent of <type>const Something*</type> is <type>const Glib::RefPtr&lt;const Something&gt;&amp;</type>.These are standard scrollbars. They should be used only to scroll another widget, such as, a <classname>Gtk::Entry</classname>, or a <classname>Gtk::Viewport</classname>, though it's usually easier to use the <classname>Gtk::ScrolledWindow</classname> widget in most cases.These dependencies have their own dependencies, including the following applications and libraries:These interactions arise from the fact that, amongst other things, a class inheriting from <classname>sigc::trackable</classname> will, via that inheritance, have a <classname>std::list</classname> object keeping track of slots created by calls to <function>sigc::mem_fun()</function> representing any of its non-static methods (more particularly it keeps a list of callbacks which will null the connected slots on its destruction). Each <classname>sigc::slot</classname> object also keeps, via <classname>sigc::slot_rep</classname>, its own <classname>sigc::trackable</classname> object to track any <classname>sigc::connection</classname> objects which it needs to inform about its demise, and also has a function to deregister itself from any <classname>sigc::trackable</classname> on disconnection or destruction. <classname>sigc::signal</classname> objects also keep lists of slots, which will be updated by a call to their <methodname>connect()</methodname> method or calls to any <classname>sigc::connection</classname> object relating to such a connection.These signals behave slightly differently. The value returned from the signal handler indicates whether it has fully "handled" the event. If the value is <literal>false</literal> then <application>gtkmm</application> will pass the event on to the next signal handler. If the value is <literal>true</literal> then no other signal handlers will need to be called.These widgets are mainly used for decoration or layout, so you won't often need to capture events on them. They are intended to have no X-Window in order to improve performance.Things are dragged from <literal>sources</literal> to be dropped on <literal>destinations</literal>. Each source and destination has infomation about the data formats that it can send or receive, provided by <classname>Gtk::TargetEntry</classname> items. A drop destination will only accept a dragged item if they both share a compatible <classname>Gtk::TargetEntry</classname> item. Appropriate signals will then be emitted, telling the signal handlers which <classname>Gtk::TargetEntry</classname> was used.This <filename>.defs</filename> file describes enum types and their possible values. It is generated by the <filename>enum.pl</filename> script which you can find in glibmm's <filename>tools</filename> directory. For instance, <placeholder-1/>This <filename>.defs</filename> file describes objects and their functions. It is generated by the <command>h2def.py</command> script which you can find in glibmm's <filename>tools/defs_gen</filename> directory. For instance, <placeholder-1/>This <varname>PROGRAMNAME_LOCALEDIR</varname> variable will be used later in the <literal>Makefile.am</literal> file, to define a macro that will be used when you initialize <application>gettext</application> in your source code.This allows language bindings to implement their own equivalents (such as C++ constructors), without using the <function>*_new()</function> function. This is often necessary so that they can actually instantiate a derived GType, to add their own hooks for signal handlers and vfuncs.This bookThis book assumes a good understanding of C++, and how to create C++ programs.This book explains key concepts of the <application>gtkmm</application> C++ API for creating user interfaces. It also introduces the main user interface elements ("widgets").This book explains key concepts of the <application>gtkmm</application> C++ API for creating user interfaces. It also introduces the main user interface elements ("widgets"). Although it mentions classes, constructors, and methods, it does not go into great detail. Therefore, for full API information you should follow the links into the reference documentation.This causes <application>gtkmm</application> to call the specified method whenever nothing else is happening. You can add a priority (lower numbers are higher priorities). There are two ways to remove the signal handler: calling <methodname>disconnect()</methodname> on the <classname>sigc::connection</classname> object, or returning <literal>false</literal> in the signal handler, which should be declared as follows:This chapter will introduce some of the most important aspects of <application>gtkmm</application> coding. These will be demonstrated with simple working example code. However, this is just a taster, so you need to look at the other chapters for more substantial information.This class implements the "Hello World" window. It's derived from <classname>Gtk::Window</classname>, and has a single <classname>Gtk::Button</classname> as a member. We've chosen to use the constructor to do all of the initialisation work for the window, including setting up the signals. Here it is, with the comments omitted:This command will build and install a series of modules and will probably take quite a long time the first time through. After the first time, however, it should go quite a bit faster since it only needs to rebuild files that changed since the last build. Alternatively, after you've built and installed <application>gtkmm</application> the first time, you can rebuild <application>gtkmm</application> by itself (without rebuilding all of its dependencies) with the command <command>jhbuild buildone gtkmm</command>.This compiler error might look like this: <placeholder-1/> or this: <placeholder-2/>This document, like so much other great software out there, was created for free by volunteers. If you are at all knowledgeable about any aspect of <application>gtkmm</application> that does not already have documentation, please consider contributing to this document.This example adds a <classname>ToolPalette</classname> and a <classname>DrawingArea</classname> to a window and allows the user to drag icons from the tool palette to the drawing area. The tool palette contains several groups of items. The combo boxes allow the user to change the style and orientation of the tool palette.This example allows copy and pasting of application-specific data, using the standard text target. Although this is simple, it's not ideal because it does not identify the <classname>Clipboard</classname> data as being of a particular type.This example creates a <classname>Gtk::EntryCompletion</classname> and associates it with a <classname>Gtk::Entry</classname> widget. The completion uses a <classname>Gtk::TreeModel</classname> of possible entries, and some additional actions.This example creates a button with a picture and a label.This example creates a window with three buttons in a grid. The first two buttons are in the upper row, from left to right. A third button is attached underneath the first button, in a new lower row, spanning two columns.This example creates two executable programs: <filename>socket</filename> and <filename>plug</filename>. The idea is that <filename>socket</filename> has an application window that will embed a widget from the <filename>plug</filename> program. The way this example is designed, <filename>plug</filename> must be running first before starting <filename>socket</filename>. To see the example in action, execute the following commands in order from within the example directory:This example displays a window with three range widgets all connected to the same adjustment, along with a couple of controls for adjusting some of the parameters mentioned above and in the section on adjustments, so you can see how they affect the way these widgets work for the user.This example has a <classname>Gtk::TreeView</classname> widget, with a <classname>Gtk::ListStore</classname> model.This example implements a container with two child widgets, one above the other. Of course, in this case it would be far simpler just to use a vertical <classname>Gtk::Box</classname>.This example implements a widget which draws a Penrose triangle.This example is identical to the <classname>ListStore</classname> example, but it uses <methodname>TreeView::append_column_editable()</methodname> instead of <methodname>TreeView::append_column()</methodname>.This example is much like the <classname>ListStore</classname> example, but derives a custom <classname>TreeView</classname> in order to override the <literal>button_press_event</literal>, and also to encapsulate the tree model code in our derived class. See the <link linkend="sec-treeview-contextmenu">TreeView Popup Context Menu</link> section.This example is much like the <classname>TreeStore</classname> example, but has 2 extra columns to indicate whether the row can be dragged, and whether it can receive drag-and-dropped rows. It uses a derived <classname>Gtk::TreeStore</classname> which overrides the virtual functions as described in the <link linkend="sec-treeview-draganddrop">TreeView Drag and Drop</link> section.This example is very similar to the <classname>ListStore</classname> example, but uses a <classname>Gtk::TreeStore</classname> model instead, and adds children to the rows.This example points out the difference of idle and timeout methods a little. If you need methods that are called periodically, and speed is not very important, then you want timeout methods. If you want methods that are called as often as possible (like calculating a fractal in background), then use idle methods.This example right-aligns a button in a window by using an <classname>Alignment</classname> widget.This example shows a <classname>Gtk::Entry</classname> widget with a named search icon, and prints text to the terminal when the icon is pressed.This example shows a <classname>Gtk::Entry</classname> widget with a progress bar.This example shows how to load a <application>Glade</application> file at runtime and access the widgets via a derived class.This example uses <classname>Gtk::Entry</classname>. It also has two <classname>CheckButton</classname>s, with which you can toggle the editable and visible flags.This exception can then be thrown by methods which are generated from _WRAP_METHOD() with the errthrow option.This has the following advantages: <placeholder-1/>This involves a variety of tools, some of them crufty, but at least they work, and has been used successfully by several projects.This involves the use of the <classname>Gtk::ActionGroup</classname>, <classname>Gtk::Action</classname>, and <classname>UIManager</classname> classes, all of which should be instantiated via their <methodname>create()</methodname> methods, which return <classname>RefPtr</classname>s.This is a full working example that defines and uses custom signals.This is demonstrated in the Popup Context Menu example.This is demonstrated in the drag_and_drop example.This is easy to correct in the C library, so do send a patch to the relevant maintainer.This is like the simple example, but it <placeholder-1/>This is one of the places where the beauty of C++ really comes out. One wouldn't think of subclassing a GTK+ widget simply to override its action method; it's just too much trouble. In GTK+, you almost always use signals to get things done, unless you're writing a new widget. But because overriding methods is so easy in C++, it's entirely practical - and sensible - to subclass a button for that purpose.This is the declaration of the <methodname>pack_start()</methodname> method:This isn't purely a <application>gtkmm</application> or GUI issue. <application>gtkmm</application> uses <application>libsigc++</application> to implement its proxy wrappers for the <application>GTK+</application> signal system, but for new, non-GTK+ signals, you can create pure C++ signals, using the <classname>sigc::signal&lt;&gt;</classname> template.This macro can be used to wrap structs which don't fit into any specialized category.This macro creates a constructor with arguments, equivalent to a <function>*_new()</function> C function. It won't actually call the <function>*_new()</function> function, but will simply create an equivalent constructor with the same argument types. It takes a C++ constructor signature, and a C function name.This macro creates a default constructor with no arguments.This macro declares a wrapper for a non-<classname>GObject</classname> struct, registered with <function>g_boxed_type_register_static()</function>.This macro declares a wrapper for a reference-counted opaque struct. The C++ wrapper cannot be directly instantiated and can only be used with <classname>Glib::RefPtr</classname>.This macro declares a wrapper for a simple assignable struct such as <classname>GdkRectangle</classname>. It is similar to <function>_CLASS_BOXEDTYPE</function>, but the C struct is not allocated dynamically.This macro declares a wrapper for a type that is derived from <classname>GObject</classname>, but whose wrapper is not derived from <classname>Gtk::Object</classname>.This macro declares a wrapper for a type that is derived from <classname>GTypeInterface</classname>.This macro declares a wrapper for a type whose wrapper is derived from <classname>Gtk::Object</classname>, such as a widget or dialog.This macro declares a wrapper for an opaque struct that has copy and free functions. The new, copy and free functions will be used to instantiate the default constructor, copy constructor and destructor.This macro generates a C++ enum to wrap a C enum. You must specify the desired C++ name and the name of the underlying C enum.This macro generates a C++ exception class, derived from Glib::Error, with a Code enum and a code() method. You must specify the desired C++ name, the name of the corresponding C enum, and the prefix for the C enum values.This macro generates initialization code for the interface.This macro generates the C++ libsigc++-style signal to wrap a C GObject signal. It actually generates a public accessor method, such as <function>signal_clicked()</function>, which returns a proxy object. <command>gmmproc</command> uses the .defs file to discover the C parameter types and the .m4 convert files to discover appropriate type conversions.This macro generates the C++ method to wrap a C GObject property. You must specify the property name and the wanted C++ type for the property. <command>gmmproc</command> uses the .defs file to discover the C type and the .m4 convert files to discover appropriate type conversions.This macro generates the C++ method to wrap a C function.This macro generates the C++ method to wrap a virtual C function.This macro is like <function>_WRAP_METHOD()</function>, but it generates only the documentation for a C++ method that wraps a C function. Use this when you must hand-code the method, but you want to use the documentation that would be generated if the method was generated.This macro will be used when you initialize <literal>gettext</literal> in your source code.This means that any method which takes a <type>const Glib::RefPtr&lt;BaseType&gt;</type> argument can also take a <type>const Glib::RefPtr&lt;DerivedType&gt;</type>. The cast is implicit, just as it would be for a normal pointer.This program contains a single class, <classname>MyArea</classname>, which is a subclass of <classname>Gtk::DrawingArea</classname> and contains an <methodname>on_draw()</methodname> member function. This function is called whenever the image in the drawing area needs to be redrawn. It is passed a <classname>Cairo::RefPtr</classname> pointer to a <classname>Cairo::Context</classname> that we use for the drawing. The actual drawing code sets the color we want to use for drawing by using <methodname>set_source_rgb()</methodname> which takes arguments defining the Red, Green, and Blue components of the desired color (valid values are between 0 and 1). After setting the color, we created a new path using the functions <methodname>move_to()</methodname> and <methodname>line_to()</methodname>, and then stroked this path with <methodname>stroke()</methodname>.This provides a directory structure for the source .hg and .ccg files and the generated .h and .cc files, with <filename>filelist.am</filename> Automake include files that can specify the various files in use, in terms of generic Automake variables. The directory structure usually looks like this, after we have renamed the directories appropriately: <placeholder-1/>This requires a number of rules to be observed when writing multi-threaded programs using <application>gtkmm</application>. These are set out below, but one point to note is that extra care is required when deriving classes from <classname>sigc::trackable</classname>, because the effects are unintuitive (see particularly points 4 and 5 below).This section describes primarily what you can expect on a Linux system, when you use <ulink url="http://www.gnu.org/software/gdb/">the gdb debugger</ulink>.This section is simply a gathering of wisdom, general style guidelines and hints for creating <application>gtkmm</application> applications.This simple application draws a curve with Cairo and displays the control points for each end of the curve.This simple example shows how to load a <application>Glade</application> file at runtime and access the widgets with <application>Gtk::Builder</application>.This tells gmmproc that the C <function>*_new()</function> has a final GError** parameter which should be ignored.This variable must mention the correct library name, and this library name must be used to form the <varname>_SOURCES</varname>, <varname>_LDFLAGS</varname>, and <varname>_LIBADD</varname> variable names. It is permissible to use variables substituted by <filename>configure</filename> like <varname>@SOMETHINGMM_API_VERSION@</varname> as part of the variable names.TimeoutsTimeouts, I/O and Idle FunctionsTo access a widget, for instance to <methodname>show()</methodname> a dialog, use the <methodname>get_widget()</methodname> method, providing the widget's name. This name should be specified in the <application>Glade</application> Properties window. If the widget could not be found, or is of the wrong type, then the pointer will be set to 0. <placeholder-1/>To achieve this, you should use the normal <classname>Gtk::TreeView</classname><methodname>insert_column()</methodname> and <methodname>append_column()</methodname> methods, then use <methodname>get_column_cell_renderer()</methodname> to get the <classname>Gtk::CellRenderer</classname> used by that column.To add a new file to the list of recent documents, in the simplest case, you only need to provide the URI. For example:To add widgets to the action area, use the <methodname>add_action_widget()</methodname> method. They will be packed alongside the default buttons. Use the <methodname>remove_action_widget()</methodname> method to remove widgets.To begin our introduction to <application>gtkmm</application>, we'll start with the simplest program possible. This program will create an empty 200 x 200 pixel window.To change the selection, specify a <classname>Gtk::TreeModel::iterator</classname> or <classname>Gtk::TreeModel::Row</classname>, like so:To change the value shown, use the <methodname>set_fraction()</methodname> method, passing a <type>double</type> between 0.0 and 1.0 to provide the new percentage.To control which rows can be selected, use the <methodname>set_select_function()</methodname> method, providing a <classname>sigc::slot</classname> callback. For instance:To convince yourself that you've done well, you may wish to add a translation for a new locale. In order to do that, go to the <filename>po</filename> subdirectory of your project and execute the following command: <placeholder-1/>To define an accelerator key for keyboard navigation, place an underscore before one of the label's characters and specify <literal>true</literal> for the optional <literal>mnemonic</literal> parameter. For instance:To determine the currently-visible page, use the <methodname>get_current_page()</methodname> method, and pass the result to <methodname>get_nth_page()</methodname>, which returns a pointer to the actual widget. To programmatically change the current page, use the <methodname>set_current_page()</methodname> method.To determine which key was pressed or released, you read the value of <varname>GdkEventKey::keyval</varname> and compare it with a constant in the <filename>&lt;gdk/gdkkeysyms.h&gt;</filename> header file. The states of modifier keys (shift, ctrl, etc.) are available as bit-flags in <varname>GdkEventKey::state</varname>.To discover the currently visible page, use the <methodname>get_current_page()</methodname> method. This returns the page number, and then calling <methodname>get_nth_page()</methodname> with that number will give you a pointer to the actual child widget.To do any drawing in <application>gtkmm</application> with Cairo, you must first create a <classname>Cairo::Context</classname> object. This class holds all of the graphics state parameters that describe how drawing is to be done. This includes information such as line width, color, the surface to draw to, and many other things. This allows the actual drawing functions to take fewer arguments to simplify the interface. In <application>gtkmm</application>, a <classname>Cairo::Context</classname> is created by calling the <methodname>Gdk::Window::create_cairo_context()</methodname> function. Since Cairo contexts are reference-counted objects, this function returns a <classname>Cairo::RefPtr&lt;Cairo::Context&gt;</classname> object.To do this, you need to call the <methodname>pulse()</methodname> method at regular intervals. You can also choose the step size, with the <methodname>set_pulse_step()</methodname> method.To draw an ellipse, you can scale the current transformation matrix by different amounts in the X and Y directions. For example, to draw an ellipse with center at <varname>x</varname>, <varname>y</varname> and size <varname>width</varname>, <varname>height</varname>: <placeholder-1/>To enable this functionality, you must create a <classname>EntryCompletion</classname> object, and provide it to the <classname>Entry</classname> widget via the <methodname>set_completion()</methodname> method.To find out what rows the user has selected, get the <classname>Gtk::TreeView::Selection</classname> object from the <classname>TreeView</classname>, like so:To find out what targets are currently available on the <classname>Clipboard</classname> for pasting, call the <methodname>request_targets()</methodname> method, specifying a method to be called with the information. For instance:To find out what type of signal handler you can connect to a signal, you can look it up in the reference documentation or the header file. Here's an example of a signal declaration you might see in the <application>gtkmm</application> headers:To force it to snap to the nearest <literal>step_increment</literal>, use <methodname>set_snap_to_ticks()</methodname>.To instantiate a <classname>Gtk::MenuBar</classname> or <classname>Gtk::Toolbar</classname> which you can actually show, you should use the <methodname>UIManager::get_widget()</methodname> method, and then add the widget to a container. For instance:To instantiate just one window, or just one of the child widgets, you can specify the name of a widget as the second parameter. For instance, <placeholder-1/>To look up recently used files, <classname>RecentManager</classname> provides several functions. To look up a specific item by its URI, you can use the <methodname>lookup_item()</methodname> function, which will return a <classname>RecentInfo</classname> class. If the specified URI did not exist in the list of recent files, <methodname>lookup_item()</methodname> throws a <classname>RecentManagerError</classname> exception. For example:To make the <classname>SpinButton</classname> 'wrap' between its upper and lower bounds, use the <methodname>set_wrap()</methodname> method.To obtain a <application>gtkmm</application> instance from a C GObject instance, use the Glib::wrap() function. For instanceTo pack widgets into a custom dialog, you should pack them into the <classname>Gtk::Box</classname>, available via <methodname>get_content_area()</methodname>. To just add a <classname>Button</classname> to the bottom of the <classname>Dialog</classname>, you could use the <methodname>add_button()</methodname> method.To prevent the user from typing non-numeric characters into the entry box, pass <literal>true</literal> to the <methodname>set_numeric()</methodname> method.To programmatically change the selected page, use the <methodname>set_current_page()</methodname> method.To receive the keyboard events, you must first call the <methodname>Gtk::Widget::add_events()</methodname> function with a bit mask of the events you're interested in. The event signal handler will receive an argument that depends on the type of event. For keyboard events it's a <type>GdkEventKey*</type>. As discribed in the <link linkend="sec-xeventsignals">appendix</link>, the event signal handler returns a <type>bool</type> value, to indicate that the signal is fully handled (<literal>true</literal>) or allow event propagation (<literal>false</literal>).To render more than one model column in a view column, you need to create the <classname>TreeView::Column</classname> widget manually, and use <methodname>pack_start()</methodname> to add the model columns to it.To respond to the user clicking on a row or range of rows, connect to the signal like so:To retrieve the state of the <classname>ToggleButton</classname>, you can use the <methodname>get_active()</methodname> method. This returns <literal>true</literal> if the button is "down". You can also set the toggle button's state, with <methodname>set_active()</methodname>. Note that, if you do this, and the state actually changes, it causes the "clicked" signal to be emitted. This is usually what you want.To see where the exception is thrown, you can use the <application>gdb</application> command <userinput>catch throw</userinput>. <placeholder-1/>To set the title of a page, use the <methodname>set_page_title()</methodname> method. The header and side images of a page can be set with the <methodname>set_page_header_image()</methodname> and <methodname>set_page_side_image()</methodname> methods.To set up <application>jhbuild</application>, follow the basic installation instructions from the <ulink url="http://developer.gnome.org/jhbuild/unstable/">jhbuild manual</ulink>. After you have installed <application>jhbuild</application>, you should copy the sample <application>jhbuild</application> configuration file into your home directory by executing the following command from the <application>jhbuild</application> directory: <screen>$ cp examples/sample.jhbuildrc ~/.jhbuildrc</screen>To show the popup menu, use <classname>Gtk::Menu</classname>'s <methodname>popup()</methodname> method, providing the button identifier and the time of activation, as provided by the <literal>button_press_event</literal> signal, which you will need to handle anyway. For instance:To simplify compilation, we use <literal>pkg-config</literal>, which is present in all (properly installed) <application>gtkmm</application> installations. This program 'knows' what compiler switches are needed to compile programs that use <application>gtkmm</application>. The <literal>--cflags</literal> option causes <literal>pkg-config</literal> to output a list of include directories for the compiler to look in; the <literal>--libs</literal> option requests the list of libraries for the compiler to link with and the directories to find them in. Try running it from your shell-prompt to see the results on your system.To specify that some text in the buffer should have specific formatting, you must define a tag to hold that formatting information, and then apply that tag to the region of text. For instance, to define the tag and its properties:To use a <application>gtkmm</application> instance with a C function that requires a C GObject instance, use the <function>gobj()</function> function to obtain a pointer to the underlying GObject instance. For instanceTo work around this, you could write a comment in the source code just before the string, telling the translators to use the special character if it is available in their languages. For english, you could then make an American English <filename>en_US.po</filename> translation which used that special character.Toggle buttonsToggleButtonToolItem ReferenceToolItemGroup ReferenceToolPaletteToolPalette ExampleToolPalette ReferenceTooltipTooltip ReferenceTooltipsTooltips are the little information windows that pop up when you leave your pointer over a widget for a few seconds. Use <methodname>set_tooltip_text()</methodname> to set a text string as a tooltip on any <classname>Widget</classname>. <classname>Gtk::ToolItem</classname>s are not <classname>Widget</classname>s, but have the same method for convenience. <classname>Gtk::Tooltip</classname> is used for more advanced tooltip usage, such as showing an image as well as text.TreeModel::iterator iter = refTreeSelection-&gt;get_selected();
if(iter) //If anything is selected
{
  TreeModel::Row row = *iter;
  //Do something with the row.
}TreeModelSort ReferenceTreeSortable ReferenceTreeStoreTreeStore, for a hierarchyTreeView - Drag And DropTreeView - Editable CellsTreeView - ListStoreTreeView - Popup Context MenuTreeView - TreeStoreTrolltech's Qt is the closest competition to <application>gtkmm</application>, so it deserves discussion.Try executing the example and increasing the system load. The upper progress bar will increase steadily; the lower one will slow down.Try to compile and run it before going on. You should see something like this:Typically our wrapper library would be called libsomethingmm. We can start by copying the <ulink url="http://git.gnome.org/cgit/mm-common/tree/skeletonmm">skeleton source tree</ulink> from the mm-common module. <placeholder-1/>UI changes can be seen more quickly, so UIs are able to improve.UIManagerUnable to predeclare structsUnfortunately, the integration with the standard iostreams is not completely foolproof. <application>gtkmm</application> converts <classname>Glib::ustring</classname>s to a locale-specific encoding (which usually is not UTF-8) if you output them to an <classname>ostream</classname> with <function>operator&lt;&lt;</function>. Likewise, retrieving <classname>Glib::ustrings</classname> from <classname>istream</classname> with <function>operator&gt;&gt;</function> causes a conversion in the opposite direction. But this scheme breaks down if you go through a <classname>std::string</classname>, e.g. by inputting text from a stream to a <classname>std::string</classname> and then implicitly converting it to a <classname>Glib::ustring</classname>. If the string contained non-ASCII characters and the current locale is not UTF-8 encoded, the result is a corrupted <classname>Glib::ustring</classname>. You can work around this with a manual conversion. For instance, to retrieve the <classname>std::string</classname> from a <classname>ostringstream</classname>: <placeholder-1/>Unix and LinuxUnless your container is a top-level window that derives from <classname>Gtk::Window</classname>, you should probably also call <methodname>Gtk::Widget::set_has_window(false)</methodname> in your constructor. This means that your container does not create its own <classname>Gdk::Window</classname>, but uses its parent's window. (Note the difference between <classname>Gtk::Window</classname> and <classname>Gdk::Window</classname>.) If your container does need its own <classname>Gdk::Window</classname>, and does not derive from <classname>Gtk::Window</classname>, you must also override the <methodname>on_realize()</methodname> method as described in the <link linkend="sec-custom-widgets">Custom Widgets</link> section. And unless your container draws directly onto the underlying <classname>Gdk::Window</classname>, you should probably call <methodname>set_redraw_on_allocate(false)</methodname> to improve performance.Unlike the Windows UCS-2 Unicode solution, this does not require any special compiler options to process string literals, and it does not result in Unicode executables and libraries which are incompatible with ASCII ones.Unlike the other widgets in this section, pane widgets contain not one but two child widgets, one in each pane. Therefore, you should use <methodname>add1()</methodname> and <methodname>add2()</methodname> instead of the <methodname>add()</methodname> method.Unusual wordsUpdate PoliciesUpdate your <literal>DISTCLEANFILES</literal>: <placeholder-1/>Use <classname>Glib::Dispatcher</classname> to invoke <application>gtkmm</application> functions from worker threads (this is dealt with in more detail in the next section).Use <methodname>Gtk::Builder::get_widget_derived()</methodname> like so: <placeholder-1/>Use GNU <application>autoconf</application> and <application>automake</application>! They are your friends :) <application>Automake</application> examines C files, determines how they depend on each other, and generates a <filename>Makefile</filename> so the files can be compiled in the correct order. <application>Autoconf</application> permits automatic configuration of software installation, handling a large number of system quirks to increase portability.Use the <methodname>append_page()</methodname>, <methodname>prepend_page()</methodname> and <methodname>insert_page()</methodname> methods to add tabbed pages to the <literal>Notebook</literal>, supplying the child widget and the name for the tab.Use the <methodname>append_page()</methodname>, <methodname>prepend_page</methodname> and <methodname>insert_page()</methodname> methods to add pages to the <classname>Assistant</classname>, supplying the child widget for each page.Use the last GError** parameter of the C function to throw an exception.Use the last GError** parameter of the C virtual function (if there is one) to throw an exception.Use these macros if you're wrapping a simple struct or boxed type that provides direct access to its data members, to create getters and setters for the data members.Use these macros to automatically provide getters and setters for a data member that is a pointer type. For the getter function, it will create two methods, one const and one non-const.Use these macros to provide getters and setters for a data member that is a <classname>GObject</classname> type that must be referenced before being returned.Used in conjunction with the <literal>slot_name</literal> option to specify the name of the glue callback function that handles extracting the slot and then calling it. The address of this callback is also passed on to the C function that the method wraps.Useful methodsUsing Adjustments the Easy WayUsing Glib::DispatcherUsing a <application>gtkmm</application> widgetUsing a ModelUsing derived widgetsUsing non-ASCII characters in stringsUsing the git version of <application>gtkmm</application>VineWe also assume that you are using autotools (e.g. <application>automake</application> and <application>autoconf</application>) to build your project, and that you are using <ulink url="http://git.gnome.org/browse/gnome-common/tree/autogen.sh"><literal>./autogen.sh</literal> from <application>gnome-common</application></ulink>, which, among other things, takes care of some <application>intltool</application> initialization.We also discuss the <classname>Gtk::Paned</classname> widget, which allows you to divide a window into two separate "panes". This widget actually contains two child widgets, but the number is fixed so it seems appropriate.We just told you that the button's <literal>clicked</literal> signal is expecting to call a method with no arguments. All signals have requirements like this - you can't hook a function with two arguments to a signal expecting none (unless you use an adapter, such as <function>sigc::bind()</function>, of course). Therefore, it's important to know what type of signal handler you'll be expected to connect to a given signal.We made a new group by simply declaring a variable, <literal>group</literal>, of type <classname>Gtk::RadioButton::Group</classname>. Then we made three radio buttons, using a constructor to make each of them part of <literal>group</literal>.We make a call to <methodname>Cairo::Context::scale()</methodname>, passing in the width and height of the drawing area. This scales the user-space coordinate system such that the width and height of the widget are both equal to 1.0 'units'. There's no particular reason to scale the coordinate system in this case, but sometimes it can make drawing operations easier.We must mention all of our <filename>.hg</filename> and <filename>.ccg</filename> files in the <filename>skeleton/src/filelist.am</filename> file, typically in the <varname>files_hg</varname> variable.We now use std::vector in several methods instead of the intermediate *Handle types to make the API clearer.We should now create our first <filename>.hg</filename> and <filename>.ccg</filename> files, to wrap one of the objects in the C library. One pair of example source files already exists: <filename>skeleton.ccg</filename> and <filename>skeleton.hg</filename>. Create copies of these files as necessary.We then hook up a signal handler to <literal>m_button</literal>'s <literal>clicked</literal> signal. This prints our friendly greeting to <literal>stdout</literal>.We told <application>gtkmm</application> to put all three <classname>RadioButton</classname>s in the same group by obtaining the group with <methodname>get_group()</methodname> and using <methodname>set_group()</methodname> to tell the other <classname>RadioButton</classname>s to share that group.We will now explain each line of the exampleWe would very much like to hear of any problems you have learning <application>gtkmm</application> with this document, and would appreciate input regarding improvements. Please see the <link linkend="chapter-contributing">Contributing</link> section for further information.We're hooking it up to the <classname>Gtk::Button</classname> object called <varname>button</varname>.We've now learned enough to look at a real example. In accordance with an ancient tradition of computer science, we now introduce Hello World, a la <application>gtkmm</application>:What if a widget reconfigures the <parameter>upper</parameter> or <parameter>lower</parameter> fields of its <classname>Adjustment</classname>, such as when a user adds more text to a text widget? In this case, it emits the <literal>changed</literal> signal.What's the difference between spacing (set when the box is created) and padding (set when elements are packed)? Spacing is added between objects, and padding is added on either side of a widget. The following figure should make it clearer:When <varname>pixbuf</varname> goes out of scope an <methodname>unref()</methodname> will happen in the background and you don't need to worry about it anymore. There's no <literal>new</literal> so there's no <literal>delete</literal>.When a constructor must be partly hand written because, for instance, the <function>*_new()</function> C function's parameters do not correspond directly to object properties, or because the <function>*_new()</function> C function does more than call <function>g_object_new()</function>, the <function>_CONSTRUCT()</function> macro may be used in the .ccg file to save some work. The <function>_CONSTRUCT</function> macro takes a series of property names and values. For instance, from <filename>button.ccg</filename>: <placeholder-1/>When a drop destination has accepted a dragged item, certain signals will be emitted, depending on what action has been selected. For instance, the user might have held down the <keycap>Shift</keycap> key to specify a <literal>move</literal> rather than a <literal>copy</literal>. Remember that the user can only select the actions which you have specified in your calls to <methodname>drag_dest_set()</methodname> and <methodname>drag_source_set()</methodname>.When a program is aborted because of an unhandled C++ exception, it's sometimes possible to use a debugger to find the location where the exception was thrown. This is more difficult than usual if the exception was thrown from a signal handler.When deriving from <classname>Gtk::Container</classname>, you should override the following virtual methods: <placeholder-1/>When deriving from <classname>Gtk::Widget</classname>, you should override the following virtual methods. The methods marked (optional) need not be overridden in all custom widgets. The base class's methods may be appropriate. <placeholder-1/>When the Button emits its <literal>clicked</literal> signal, <methodname>on_button_clicked()</methodname> will be called.When the application runs, the <application>gettext</application> library checks the system-wide directory to see if there is a <filename>.mo</filename> file for the user's locale environment (you can set the locale with, for instance, "export LANG=de_DE.UTF-8" from a bash console). Later, when the program reaches a <literal>gettext</literal> call, it looks for a translation of a particular string. If none is found, the original string is used.When the mouse is over the button and a mouse button is pressed, <methodname>on_button_press()</methodname> will be called.When the user asks to copy some data, you should tell the <classname>Clipboard</classname> what targets are available, and provide the callback methods that it can use to get the data. At this point you should store a copy of the data, to be provided when the clipboard calls your callback method in response to a paste.When the user asks to paste data from the <classname>Clipboard</classname>, you should request a specific format and provide a callback method which will be called with the actual data. For instance:When the user enters arbitrary text, it may not be enough to connect to the <literal>changed</literal> signal, which is emitted for every typed character. It is not emitted when the user presses the Enter key. Pressing the Enter key or moving the keyboard focus to another widget may signal that the user has finished entering text. To be notified of these events, connect to the <classname>Entry</classname>'s <literal>activate</literal> and <literal>focus_out_event</literal> signals, like so <placeholder-1/> The <literal>changed</literal> signals of <classname>ComboBox</classname> and <classname>Entry</classname> are both emitted for every change. It doesn't matter which one you connect to. But only <classname>Entry</classname>'s <literal>focus_out_event</literal> signal is useful here.When using <function>_CLASS_GOBJECT()</function>, the constructors should be protected (rather than public) and each constructor should have a corresponding <function>_WRAP_CREATE()</function> in the public section. This prevents the class from being instantiated without using a <classname>RefPtr</classname>. For instance: <placeholder-1/>When using a <classname>Gtk::TreeStore</classname>, the rows can have child rows, which can have their own children in turn. Use <methodname>Gtk::TreeModel::Row::children()</methodname> to get the container of child <classname>Row</classname>s: <placeholder-1/>When using this simple <methodname>append_column()</methodname> override, the <classname>TreeView</classname> will display the model data with an appropriate <classname>CellRenderer</classname>. For instance, strings and numbers are shown in a simple <classname>Gtk::Entry</classname> widget, and booleans are shown in a <classname>Gtk::CheckButton</classname>. This is usually what you need. For other column types you must either connect a callback that converts your type into a string representation, with <methodname>TreeViewColumn::set_cell_data_func()</methodname>, or derive a custom <classname>CellRenderer</classname>. Note that (unsigned) short is not supported by default - You could use (unsigned) int or (unsigned) long as the column type instead.When you downloaded <application>jhbuild</application> from the git repository, you got a number of <filename>.modules</filename> files, specifying dependencies between modules. By default <application>jhbuild</application> does not use the downloaded versions of these files, but reads the latest versions in the git repository. This is usually what you want. If you don't want it, use the <varname>use_local_modulesets</varname> variable in <filename>.jhbuildrc</filename>.When you select a choice from the drop-down menu, the value from this column will be placed in the <classname>Entry</classname>.When you write in the entry, a key release event will be emitted, which will go first to the toplevel window (<classname>Gtk::Window</classname>), since we have one event handler set to be called before, that's what is called first (<methodname>windowKeyReleaseBefore()</methodname>). Then the default handler is called (which we have overridden), and after that the event is sent to the widget that has focus, the <classname>Entry</classname> in our example and, depending on whether we let it propagate, it can reach the <classname>Grid</classname>'s and the <classname>Window</classname>'s event handlers. If it propagates, the text you're writing will appear in the <classname>Label</classname> above the <classname>Entry</classname>.Whenever you press or release a key, an event is emitted. You can connect a signal handler to handle such events.Why use <application>gtkmm</application> instead of GTK+?Widget ReferenceWidget::on_expose_event() was replaced by Widget::on_draw(), which assumes that cairomm is used for drawing, via the provided <classname>Cairo::Context</classname> and does not require you to call <methodname>Cairo::Context::clip()</methodname>.WidgetsWidgets Without X-WindowsWidgets and ChildAnchorsWidgets are arranged inside container widgets such as frames and notebooks, in a hierarchy of widgets within widgets. Some of these container widgets, such as <classname>Gtk::Grid</classname>, are not visible - they exist only to arrange other widgets. Here is some example code that adds 2 <classname>Gtk::Button</classname> widgets to a <classname>Gtk::Box</classname> container widget: <placeholder-1/> and here is how to add the <classname>Gtk::Box</classname>, containing those buttons, to a <classname>Gtk::Frame</classname>, which has a visible frame and title: <placeholder-2/>With Cairo, the same function is used to draw arcs, circles, or ellipses: <methodname>Cairo::Context::arc()</methodname>. This function takes five arguments. The first two are the coordinates of the center point of the arc, the third argument is the radius of the arc, and the final two arguments define the start and end angle of the arc. All angles are defined in radians, so drawing a circle is the same as drawing an arc from 0 to 2 * M_PI radians. An angle of 0 is in the direction of the positive X axis (in user-space). An angle of M_PI/2 radians (90 degrees) is in the direction of the positive Y axis (in user-space). Angles increase in the direction from the positive X axis toward the positive Y axis. So with the default transformation matrix, angles increase in a clockwise direction. (Remember that the positive Y axis points downwards.)Working with gtkmm's Source CodeWrapping <classname>GList*</classname> and <classname>GSList*</classname> return types: You must discover whether the caller should free the list and whether it should release the items in the list, again by reading the documentation of the C function. With this information you can choose the ownership (none, shallow or deep) for the m4 conversion rule, which you should probably put directly into the .hg file because the ownership depends on the function rather than the type. For instance: <placeholder-1/>Wrapping C Libraries with gmmprocWriting signal handlersWriting the vfuncs .defsX Event signalsX events are described in more detail in the <link linkend="sec-xeventsignals">X Event signals</link> section in the appendix.X events differ in some ways from other signals. These differences are described in the <link linkend="sec-xeventsignals">X Event signals</link> section in the appendix. Here we will use keyboard events to show how X events can be used in a program.Yes, that's correct: a Window can contain at most one widget. How, then, can we use a window for anything useful? By placing a multiple-child container in the window. The most useful container widgets are <classname>Gtk::Grid</classname> and <classname>Gtk::Box</classname>.You are likely to encounter some problems in the library that you are wrapping, particularly if it is a new project. Here are some common problems, with solutions.You are not guaranteed to get the <literal>Gtk::SizeRequestMode</literal> that you request. Therefore all four of the <methodname>get_preferred_xxx_vfunc()</methodname> methods must return sensible values.You can adjust the position of the divider using the <methodname>set_position()</methodname> method, and you will probably need to do so.You can also cast to a derived type, but the syntax is a little different than with a normal pointer.You can also connect to <classname>CellRenderer</classname> signals to detect user actions. For instance:You can also specify a signal handler when calling <methodname>ActionGroup::add()</methodname>. This signal handler will be called when the action is activated via either a menu item or a toolbar button.You can also use <methodname>get_tag_table()</methodname> to get, and maybe modify, the <classname>TextBuffer</classname>'s default <classname>TagTable</classname> instead of creating one explicitly.You can apply more than one <classname>Tag</classname> to the same text, by using <methodname>apply_tag()</methodname> more than once, or by using <methodname>insert_with_tags()</methodname>. The <classname>Tag</classname>s might specify different values for the same properties, but you can resolve these conflicts by using <methodname>Tag::set_priority()</methodname>.You can build several modules by setting the <varname>modules</varname> variable to a meta-package, e.g. <literal>meta-gnome-core</literal>, or listing more than one module name. The <varname>modules</varname> variable specifies which modules will be built when you don't explicitly specify anything on the command line. You can always build a different moduleset later by specifying it on the commandline (e.g. <command>jhbuild build gtkmm</command>).You can cast <classname>RefPtr</classname>s to base types, just like normal pointers.You can copy <classname>RefPtr</classname>s, just like normal pointers. But unlike normal pointers, you don't need to worry about deleting the underlying instance.You can create a new <classname>RecentManager</classname>, but you'll most likely just want to use the default one. You can get a reference to the default <classname>RecentManager</classname> with <methodname>get_default()</methodname>.You can dereference a smartpointer with the -&gt; operator, to call the methods of the underlying instance, just like a normal pointer.You can dereference the iterator to get the Row:You can draw very sophisticated shapes using Cairo, but the methods to do so are quite basic. Cairo provides methods for drawing straight lines, curved lines, and arcs (including circles). These basic shapes can be combined to create more complex shapes and paths which can be filled with solid colors, gradients, patterns, and other things. In addition, Cairo can perform complex transformations, do compositing of images, and render antialiased text.You can embed widgets, such as <classname>Gtk::Button</classname>s, in the text. Each such child widget needs a <classname>ChildAnchor</classname>. ChildAnchors are associated with <classname>iterators</classname>. For instance, to create a child anchor at a particular position, use <methodname>Gtk::TextBuffer::create_child_anchor()</methodname>:You can modify the update policy using the <methodname>set_update_policy()</methodname> method, specifying either <literal>Gtk::UPDATE_ALWAYS</literal> or <literal>Gtk::UPDATE_IF_VALID</literal>. <literal>Gtk::UPDATE_ALWAYS</literal> causes the <classname>SpinButton</classname> to ignore errors encountered while converting the text in the entry box to a numeric value. This setting also therefore allows the <classname>SpinButton</classname> to accept non-numeric values. You can force an immediate update using the <methodname>update()</methodname> method.You can set the <emphasis>margin</emphasis> and <emphasis>expand</emphasis> properties of the child <classname>Widget</classname>s to control their spacing and their behaviour when the Grid is resized.You can set the spinbutton's value using the <methodname>set_value()</methodname> method, and retrieve it with <methodname>get_value()</methodname>.You can specify a <classname>Gtk::TreeModel</classname> when constructing the <classname>Gtk::TreeView</classname>, or you can use the <methodname>set_model()</methodname> method, like so:You can specify a name for the <classname>Tag</classname> when using the <methodname>create()</methodname> method, but it is not necessary.You can stop the timeout method by returning <literal>false</literal> from your signal handler. Therefore, if you want your method to be called repeatedly, it should return <literal>true</literal>.You can then connect to the appropriate "edited" signal. For instance, connect to <methodname>Gtk::CellRendererText::signal_edited()</methodname>, or <methodname>Gtk::CellRendererToggle::signal_toggled()</methodname>. If the column contains more than one <classname>CellRenderer</classname> then you will need to use <methodname>Gtk::TreeView::get_column()</methodname> and then call <methodname>get_cell_renderers()</methodname> on that view Column.You can then connect to the signal using the same syntax used when connecting to <application>gtkmm</application> signals. For instance, <placeholder-1/>You can then use the <methodname>get_iter()</methodname> method later to create an iterator for the <classname>Mark</classname>'s new position.You can use <application>Glade</application> to layout your own custom widgets derived from <application>gtkmm</application> widget classes. This keeps your code organized and encapsulated. Of course you won't see the exact appearance and properties of your derived widget in <application>Glade</application>, but you can specify its location and child widgets and the properties of its <application>gtkmm</application> base class.You can use C APIs which do not yet have convenient C++ interfaces. It is generally not a problem to use C APIs from C++, and <application>gtkmm</application> helps by providing access to the underlying C object, and providing an easy way to create a C++ wrapper object from a C object, provided that the C API is also based on the GObject system.You can use the <methodname>append_column()</methodname> method to tell the View that it should display certain Model columns, in a certain order, with a certain column title.You can use the <methodname>operator[]</methodname> override to get the data in a particular column in a row, specifiying the <classname>TreeModelColumn</classname> used to create the model.You can use the <methodname>operator[]</methodname> override to set the data for a particular column in the row, specifying the <classname>TreeModelColumn</classname> used to create the model.You can use the <methodname>toggled()</methodname> method to toggle the button, rather than forcing it to be up or down: This switches the button's state, and causes the <literal>toggled</literal> signal to be emitted.You can usually pretend that <classname>Gtk::Clipboard</classname> is a singleton. You can get the default clipboard instance with <methodname>Gtk::Clipboard::get()</methodname>. This is probably the only clipboard you will ever need.You could just declare that signal as a public member variable, but some people find that distasteful and prefer to make it available via an accessor method, like so: <placeholder-1/>You could then encapsulate the manipulation of the child widgets in the constructor of the derived class, maybe using <methodname>get_widget()</methodname> or <methodname>get_widget_derived()</methodname> again. For instance, <placeholder-1/>You don't always need to call the parent's method; there are times when you might not want to. Note that we called the parent method <emphasis>after</emphasis> writing "Hello World", but we could have called it before. In this simple example, it hardly matters much, but there are times when it will. With signals, it's not quite so easy to change details like this, and you can do something here which you can't do at all with connected signal handlers: you can call the parent method in the <emphasis>middle</emphasis> of your custom code.You have no way of getting a bare <classname>Gdk::Pixbuf</classname>. In the example, <varname>pixbuf</varname> is a smart pointer, so you can do this, much like a normal pointer: <placeholder-1/>You may add a custom tab to the print dialog: <placeholder-1/>You may be wondering how to make <application>gtkmm</application> do useful work while it's idling along. Happily, you have several options. Using the following methods you can create a timeout method that will be called every few milliseconds.You might also derive non-widget classes from Gtk::Object so they can be used without <classname>Glib::RefPtr</classname>. For instance, they could then be instantiated with <function>Gtk::manage()</function> or on the stack as a member variable. This is convenient, but you should use this only when you are sure that true reference-counting is not needed. We consider it useful for widgets.You might be surprised to learn that <application>gtkmm</application> doesn't use <classname>std::string</classname> in its interfaces. Instead it uses <classname>Glib::ustring</classname>, which is so similar and unobtrusive that you could actually pretend that each <classname>Glib::ustring</classname> is a <classname>std::string</classname> and ignore the rest of this section. But read on if you want to use languages other than English in your application.You might need to react to every change of selection in the ComboBox, for instance to update other widgets. To do so, you should handle the <literal>changed</literal> signal. For instance:You might not anticipate the need to support additional languages, but you can never rule it out. And it's easier to develop the application properly in the first place rather than retrofitting later.You might then handle the <classname>ToolButton</classname>'s <literal>clicked</literal> signal. Alternatively, you could allow the item to be dragged to another widget, by calling <methodname>Gtk::ToolPalette::add_drag_dest()</methodname> and then using <methodname>Gtk::ToolPalette::get_drag_item()</methodname> in the other widget's <literal>drag_data_received</literal> signal handler.You might want to associate extra data with each row. If so, just add it as a Model column, but don't add it to the View.You might want to be notified whenever the user types in a text entry widget. <classname>Gtk::Entry</classname> provides two signals, <literal>activate</literal> and <literal>changed</literal>, for this purpose. <literal>activate</literal> is emitted when the user presses the Enter key in a text-entry widget; <literal>changed</literal> is emitted when the text in the widget changes. You can use these, for instance, to validate or filter the text the user types. Moving the keyboard focus to another widget may also signal that the user has finished entering text. The <literal>focus_out_event</literal> signal that <classname>Gtk::Entry</classname> inherits from <classname>Gtk::Widget</classname> can notify you when that happens. The <link linkend="sec-comboboxentry">ComboBox with an Entry</link> section contains example programs that use these signals.You might want to include additional source files that will not be generated by <command>gmmproc</command> from <filename>.hg</filename> and <filename>.ccg</filename> files. You can simply place these in your <filename>libsomething/libsomethingmm</filename> directory and mention them in the <filename>Makefile.am</filename> in the <varname>files_extra_h</varname> and <varname>files_extra_cc</varname> variables.You might wish to reuse documentation that exists for the C library that you are wrapping. GTK-style C libraries typically use gtk-doc and therefore have source code comments formatted for gtk-doc and some extra documentation in .sgml and .xml files. The docextract_to_xml.py script, from glibmm's <filename>tools/defs_gen</filename> directory, can read these files and generate an .xml file that <command>gmmproc</command> can use to generate doxygen comments. <command>gmmproc</command> will even try to transform the documentation to make it more appropriate for a C++ API.You must call the base class's constructor in the initialization list, providing the C pointer. For instance, <placeholder-1/>You must edit the source code of your own <filename>generate_extra_defs</filename> tool in order to generate the <filename>.defs</filename> for the GObject C types that you wish to wrap. In the skeleton source tree, the source file is named <filename>codegen/extradefs/generate_extra_defs_skeleton.cc</filename>. If not done so already, the file should be renamed, with the basename of your new binding substituted for the <varname>skeleton</varname> placeholder. The <filename>codegen/Makefile.am</filename> file should also mention the new source filename.You must set the optional parameter <literal>after = false</literal> in the call to <literal>signal_command_line().connect()</literal>, because your signal handler must be called before the default signal handler. You must also call <methodname>Gio::Application::activate()</methodname> in the signal handler, unless you want your application to exit without showing its main window. (<classname>Gio::Application</classname> is a base class of <classname>Gtk::Application</classname>.)You need to specify the <classname>Alignment</classname>'s characteristics to the constructor, or to the <methodname>set()</methodname> method. In particular, you won't notice much effect unless you specify a number other than 1.0 for the <literal>xscale</literal> and <literal>yscale</literal> parameters, because 1.0 simply means that the child widget will expand to fill all available space.You never know how much space a string will take on screen when translated. It might very possibly be twice the size of the original English string. Luckily, most <application>gtkmm</application> widgets will expand at runtime to the required size.You probably won't ever need to attach a handler to this signal, unless you're writing a new type of range widget.You should avoid C-style pointer arithmetic, and functions such as strlen(). In UTF-8, each character might need anywhere from 1 to 6 bytes, so it's not possible to assume that the next byte is another character. <classname>Glib::ustring</classname> worries about the details of this for you so you can use methods such as Glib::ustring::substr() while still thinking in terms of characters instead of bytes.You should avoid cryptic abbreviations, slang, or jargon. They are usually difficult to translate, and are often difficult for even native speakers to understand. For instance, prefer "application" to "app"You should avoid including the C header from your C++ header, to avoid polluting the global namespace, and to avoid exporting unnecessary public API. But you will need to include the necessary C headers from your .ccg file.You should be very careful when installing to standard system prefixes such as <filename>/usr</filename>. Linux distributions install software packages to <filename>/usr</filename>, so installing a source package to this prefix could corrupt or conflict with software installed using your distribution's package-management system. Ideally, you should use a separate prefix for all software you install from source.You should not declare these types yourself. You should instead use whatever Standard C++ container you prefer. glibmm will do the conversion for you. Here are some of these intermediate types: <placeholder-1/>You should save the chosen <classname>Gtk::PageSetup</classname> so you can use it again if the page setup dialog is shown again.You should then cast that <classname>Gtk::CellRenderer*</classname> to the specific <classname>CellRenderer</classname> that you expect, so you can use specific API.You specify the <classname>ColumnRecord</classname> when creating the Model, like so:You still need C++ code to deal with User Interface changes triggered by user actions, but using <application>Gtk::Builder</application> for the widget layout allows you to focus on implementing that functionality.You will typically use this macro when the class already derives from Gtk::Object. For instance, you will use it when wrapping a GTK+ Widget, because Gtk::Widget derives from Gtk::Object.You've probably noticed that <application>gtkmm</application> windows seem "elastic" - they can usually be stretched in many different ways. This is due to the <emphasis>widget packing</emphasis> system.Your application doesn't need to wait for clipboard operations, particularly between the time when the user chooses Copy and then later chooses Paste. Most <classname>Gtk::Clipboard</classname> methods take <classname>sigc::slot</classname>s which specify callback methods. When <classname>Gtk::Clipboard</classname> is ready, it will call these methods, either providing the requested data, or asking for data.Your callback will then provide the stored data when the user chooses to paste the data. For instance:Your derived class must have a constructor that takes a pointer to the underlying C type, and the <classname>Gtk::Builder</classname> instance. All relevant classes of <application>gtkmm</application> typedef their underlying C type as <classname>BaseObjectType</classname> (<classname>Gtk::Dialog</classname> typedefs <classname>BaseObjectType</classname> as <type>GtkDialog</type>, for instance).Your existing knowledge of C++ will help you with <application>gtkmm</application> as it would with any library. Unless we state otherwise, you can expect <application>gtkmm</application> classes to behave like any other C++ class, and you can expect to use your existing C++ techniques with <application>gtkmm</application> classes.Your implementation of the <methodname>child_type_vfunc()</methodname> method should report the type of widget that may be added to your container, if it is not yet full. This is usually <methodname>Gtk::Widget::get_type()</methodname> to indicate that the container may contain any class derived from <classname>Gtk::Widget</classname>. If the container may not contain any more widgets, then this method should return <literal>G_TYPE_NONE</literal>.Your library must be initialized before it can be used, to register the new types that it makes available. Also, the C library that you are wrapping might have its own initialization function that you should call. You can do this in an <function>init()</function> function that you can place in hand-coded <filename>init.h</filename> and <filename>init.cc</filename> files. This function should initialize your dependencies (such as the C function, and <application>gtkmm</application>) and call your generated <function>wrap_init()</function> function. For instance: <placeholder-1/>_CLASS_BOXEDTYPE_CLASS_BOXEDTYPE( C++ class, C class, new function, copy function, free function )_CLASS_BOXEDTYPE_STATIC_CLASS_BOXEDTYPE_STATIC( C++ class, C class )_CLASS_GENERIC_CLASS_GENERIC( C++ class, C class )_CLASS_GOBJECT_CLASS_GOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )_CLASS_GTKOBJECT_CLASS_GTKOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )_CLASS_GTKOBJECT()_CLASS_INTERFACE_CLASS_INTERFACE( C++ class, C class, C casting macro, C interface struct, Base C++ class (optional), Base C class (optional) )_CLASS_OPAQUE_COPYABLE_CLASS_OPAQUE_COPYABLE( C++ class, C class, new function, copy function, free function )_CLASS_OPAQUE_REFCOUNTED_CLASS_OPAQUE_REFCOUNTED( C++ class, C class, new function, ref function, unref function )_CTOR_DEFAULT_DEFS()_IGNORE / _IGNORE_SIGNAL_IGNORE(C function name 1, C function name2, etc)_IGNORE_SIGNAL(C signal name 1, C signal name2, etc)_IMPLEMENTS_INTERFACE_IMPLEMENTS_INTERFACE()_IMPLEMENTS_INTERFACE(C++ interface name)_MEMBER_GET / _MEMBER_SET_MEMBER_GET(C++ name, C name, C++ type, C type)_MEMBER_GET(x, x, int, int)_MEMBER_GET_GOBJECT / _MEMBER_SET_GOBJECT_MEMBER_GET_GOBJECT(C++ name, C name, C++ type, C type)_MEMBER_GET_PTR / _MEMBER_SET_PTR_MEMBER_GET_PTR(C++ name, C name, C++ type, C type)_MEMBER_SET(C++ name, C name, C++ type, C type)_MEMBER_SET_GOBJECT(C++ name, C name, C++ type, C type)_MEMBER_SET_PTR(C++ name, C name, C++ type, C type)_PINCLUDE()_WRAP_CTOR_WRAP_ENUM_WRAP_ENUM_DOCS_ONLY_WRAP_GERROR_WRAP_METHOD_WRAP_METHOD( C++ method signature, C function name)_WRAP_METHOD_DOCS_ONLY_WRAP_METHOD_DOCS_ONLY(C function name)_WRAP_PROPERTY_WRAP_PROPERTY(C property name, C++ type)_WRAP_SIGNAL_WRAP_SIGNAL( C++ signal handler signature, C signal name)_WRAP_VFUNC_WRAP_VFUNC( C++ method signature, C function name)adj-&gt;signal_value_changed().connect(sigc::bind&lt;MyPicture*&gt;(sigc::mem_fun(*this,
    &amp;cb_rotate_picture), picture));adjustment-&gt;signal_changed();and connect it to the scale widget's adjustment like this:and thenatkmmbinding_namebindtextdomain(GETTEXT_PACKAGE, PROGRAMNAME_LOCALEDIR);
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
textdomain(GETTEXT_PACKAGE);boolbool DemoWindow::select_function(
    const Glib::RefPtr&lt;Gtk::TreeModel&gt;&amp; model,
    const Gtk::TreeModel::Path&amp; path, bool)
{
  const Gtk::TreeModel::iterator iter = model-&gt;get_iter(path);
  return iter-&gt;children().empty(); // only allow leaf nodes to be selected
}bool ExampleWindow::on_button_press_event(GdkEventButton* event)
{
  if( (event-&gt;type == GDK_BUTTON_PRESS) &amp;&amp;
      (event-&gt;button == 3) )
  {
    m_Menu_Popup-&gt;popup(event-&gt;button, event-&gt;time);
    return true; //It has been handled.
  }
  else
    return false;
}bool MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  Glib::RefPtr&lt;Gdk::Pixbuf&gt; image = Gdk::Pixbuf::create_from_file("myimage.png");
  // Draw the image at 110, 90, except for the outermost 10 pixels.
  Gdk::Cairo::set_source_pixbuf(cr, image, 100, 80);
  cr-&gt;rectangle(110, 90, image-&gt;get_width()-20, image-&gt;get_height()-20);
  cr-&gt;fill();
  return true;
}buttons examplecairocairommcell.property_editable() = true;class HelloWorld : public Gtk::Window
{

public:
  HelloWorld();
  virtual ~HelloWorld();

protected:
  //Signal handlers:
  virtual void on_button_clicked();

  //Member widgets:
  Gtk::Button m_button;
};class ModelColumns : public Gtk::TreeModelColumnRecord
{
public:

  ModelColumns()
    { add(m_col_text); add(m_col_number); }

  Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_text;
  Gtk::TreeModelColumn&lt;int&gt; m_col_number;
};

ModelColumns m_Columns;class RadioButtons : public Gtk::Window
{
public:
    RadioButtons();

protected:
    Gtk::RadioButton m_rb1, m_rb2, m_rb3;
};

RadioButtons::RadioButtons()
  : m_rb1("button1"),
    m_rb2("button2"),
    m_rb3("button3")
{
    Gtk::RadioButton::Group group = m_rb1.get_group();
    m_rb2.set_group(group);
    m_rb3.set_group(group);
}class RadioButtons : public Gtk::Window
{
public:
    RadioButtons();
};

RadioButtons::RadioButtons()
{
    Gtk::RadioButton::Group group;
    Gtk::RadioButton *m_rb1 = Gtk::manage(
      new Gtk::RadioButton(group,"button1"));
    Gtk::RadioButton *m_rb2 = manage(
      new Gtk::RadioButton(group,"button2"));
      Gtk::RadioButton *m_rb3 = manage(
        new Gtk::RadioButton(group,"button3"));
}clickedconfigure.acconstversioncontext-&gt;save();
context-&gt;translate(x, y);
context-&gt;scale(width / 2.0, height / 2.0);
context-&gt;arc(0.0, 0.0, 1.0, 0.0, 2 * M_PI);
context-&gt;restore();custom_c_callbackcustom_default_handlercustom_vfunccustom_vfunc_callbackdeprecateddisplay_message("Getting ready for i18n.");display_message(_("Getting ready for i18n."));doubleenterenumserrthrowevent_box.add(child_widget);flags: Used only for drag and drop, this specifies whether the data may be dragged to other widgets and applications, or only to the same ones.functionsg++ simple.cc -o simple `pkg-config gtkmm-3.0 --cflags --libs`gbooleangchar*gdk-pixbufgdoublegettext manualgintglibglibmmgmmproc Parameter Processinggnomemm_hellogtk.defsgtk_enums.defsgtk_methods.defsgtk_signals.defsgtk_vfuncs.defsgtkmmgtkmm_helloguintgunicharifdefinfo: An identifier which will be sent to your signals to tell you which TargetEntry was used.intint cols_count = m_TreeView.append_column_editable("Alex", m_columns.alex);
Gtk::TreeViewColumn* pColumn = m_TreeView.get_column(cols_count-1);
if(pColumn)
{
  Gtk::CellRendererToggle* pRenderer =
    static_cast&lt;Gtk::CellRendererToggle*&gt;(pColumn-&gt;get_first_cell());
  pColumn-&gt;add_attribute(pRenderer-&gt;property_visible(), m_columns.visible);
  pColumn-&gt;add_attribute(pRenderer-&gt;property_activatable(), m_columns.world);int main(int argc, char** argv)
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  HelloWorld helloworld;
  return app-&gt;run(helloworld);
}intltool-update --potleavelib_LTLIBRARIESlibsigc++ 2.0m4 Conversionsm4 Initializationsm_TextView.add_child_at_anchor(m_Button, refAnchor);m_TreeView.append_column("Messages", m_Columns.m_col_text);m_TreeView.set_model(m_refListStore);m_box.pack_start(m_Button1);
m_box.pack_start(m_Button2);m_button1.signal_clicked().connect( sigc::mem_fun(*this,
  &amp;HelloWorld::on_button_clicked) );m_combo.set_entry_text_column(m_columns.m_col_name);m_combo.signal_changed().connect( sigc::mem_fun(*this,
      &amp;ExampleWindow::on_combo_changed) );m_frame.add(m_box);m_rb2.set_group(m_rb1.get_group()); //doesn't workm_refActionGroup = Gtk::ActionGroup::create();

m_refActionGroup-&gt;add( Gtk::Action::create("MenuFile", "_File") );
m_refActionGroup-&gt;add( Gtk::Action::create("New", "_New"),
  sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_new) );
m_refActionGroup-&gt;add( Gtk::Action::create("ExportData", "Export Data"),
  sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_open) );
m_refActionGroup-&gt;add( Gtk::Action::create("Quit", "_Quit"),
  sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_quit) );m_refTreeSelection-&gt;set_select_function( sigc::mem_fun(*this,
    &amp;DemoWindow::select_function) );modules = [ 'gtkmm' ]moduleset = 'gnome-suites-core-deps-3.12'no_default_handlerno_slot_copyobjects (GObjects, widgets, interfaces, boxed-types and plain structs)orpangommpkg-configpressedpropertiesrefBuffer-&gt;apply_tag(refTagMatch, iterRangeStart, iterRangeStop);refBuffer-&gt;insert_with_tag(iter, "Some text", refTagMatch);refClipboard-&gt;request_contents("example_custom_target",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_received) );refClipboard-&gt;request_targets( sigc::mem_fun(*this,
    &amp;ExampleWindow::on_clipboard_received_targets) );refTreeSelection-&gt;selected_foreach_iter(
    sigc::mem_fun(*this, &amp;TheClass::selected_row_callback) );

void TheClass::selected_row_callback(
    const Gtk::TreeModel::iterator&amp; iter)
{
  TreeModel::Row row = *iter;
  //Do something with the row.
}refTreeSelection-&gt;set_mode(Gtk::SELECTION_MULTIPLE);refTreeSelection-&gt;signal_changed().connect(
    sigc::mem_fun(*this, &amp;Example_IconTheme::on_selection_changed)
);refreturnrefreturn_ctypereleasedreturn app-&gt;run(window);row[m_Columns.m_col_text] = "sometext";signalsslot_callbackslot_namesrc/main.cc
src/other.ccstd::cout &lt;&lt; Glib::ustring::compose(
             _("Current amount: %1 Future: %2"), amount, future) &lt;&lt; std::endl;

label.set_text(Glib::ustring::compose(_("Really delete %1 now?"), filename));std::cout &lt;&lt; _("Current amount: ") &lt;&lt; amount
          &lt;&lt; _(" Future: ") &lt;&lt; future &lt;&lt; std::endl;

label.set_text(_("Really delete ") + filename + _(" now?"));std::ostringstream output;
output.imbue(std::locale("")); // use the user's locale for this stream
output &lt;&lt; percentage &lt;&lt; " % done";
label-&gt;set_text(Glib::locale_to_utf8(output.str()));std::stringstd::string uses 8 bit per character, but 8 bits aren't enough to encode languages such as Arabic, Chinese, and Japanese. Although the encodings for these languages have now been specified by the Unicode Consortium, the C and C++ languages do not yet provide any standardised Unicode support. GTK+ and GNOME chose to implement Unicode using UTF-8, and that's what is wrapped by Glib::ustring. It provides almost exactly the same interface as std::string, along with automatic conversions to and from std::string.std::vector&lt; Glib::RefPtr&lt;Gtk::RecentInfo&gt; &gt; info_list = recent_manager-&gt;get_items();target: A name, such as "STRING"translator-creditstypedef Gtk::TreeModel::Children type_children; //minimise code length.
type_children children = refModel-&gt;children();
for(type_children::iterator iter = children.begin();
    iter != children.end(); ++iter)
{
  Gtk::TreeModel::Row row = *iter;
  //Do something with the row - see above for set/get.
}vfuncsvfuncs (function pointer member fields in structs), written by hand.void ExampleWindow::on_button_delete()
{
  Glib::RefPtr&lt;Gtk::TreeSelection&gt; refTreeSelection =
      m_treeview.get_selection();
  if(refTreeSelection)
  {
    Gtk::TreeModel::iterator sorted_iter =
        m_refTreeSelection-&gt;get_selected();
    if(sorted_iter)
    {
      Gtk::TreeModel::iterator iter =
          m_refModelSort-&gt;convert_iter_to_child_iter(sorted_iter);
      m_refModel-&gt;erase(iter);
    }
  }
}void ExampleWindow::on_clipboard_get(
    Gtk::SelectionData&amp; selection_data, guint /* info */)
{
  const std::string target = selection_data.get_target();

  if(target == "example_custom_target")
    selection_data.set("example_custom_target", m_ClipboardStore);
}void ExampleWindow::on_clipboard_received(
    const Gtk::SelectionData&amp; selection_data)
{
  Glib::ustring clipboard_data = selection_data.get_data_as_string();
  //Do something with the pasted data.
}void ExampleWindow::on_clipboard_received_targets(
  const std::vector&lt;Glib::ustring&gt;&amp; targets)
{
  const bool bPasteIsPossible =
    std::find(targets.begin(), targets.end(),
      example_target_custom) != targets.end();

  // Enable/Disable the Paste button appropriately:
  m_Button_Paste.set_sensitive(bPasteIsPossible);
}void cb_rotate_picture (MyPicture* picture)
{
  picture-&gt;set_rotation(adj-&gt;get_value());
...void doSomething(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; context, int x)
{
    context-&gt;save();
    // change graphics state
    // perform drawing operations
    context-&gt;restore();
}void drag_dest_set(const std::vector&lt;Gtk::TargetEntry&gt;&amp; targets,
    Gtk::DestDefaults flags, Gdk::DragAction actions);void drag_source_set(const std::vector&lt;Gtk::TargetEntry&gt;&amp; targets,
      Gdk::ModifierType start_button_mask, Gdk::DragAction actions);void pack_start(Gtk::Widget&amp; child,
                Gtk::PackOptions options = Gtk::PACK_EXPAND_WIDGET,
                guint padding = 0);where <parameter>condition</parameter> is as specified above. As usual the slot is created with <function>sigc::mem_fun()</function> (for a member method of an object), or <function>sigc::ptr_fun()</function> (for a function).wrap_init_flagsxgettext -a -o my-strings --omit-header *.cc *.hProject-Id-Version: gtkmm-documentation.tutorial.master
POT-Creation-Date: 2013-11-22 09:41+0000
PO-Revision-Date: 2013-11-22 17:12+0100
Last-Translator: Daniel Mustieles <daniel.mustieles@gmail.com>
Language-Team: Español <gnome-es-list@gnome.org>
Language: es
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Plural-Forms: nplurals=2; plural=(n!=1);
X-Generator: Gtranslator 2.91.6

        GtkSizeRequestMode gtk_widget_get_request_mode(GtkWidget* widget);
      
        GtkToolItem* gtk_tool_button_new(GtkWidget* icon_widget, const gchar*
        label);
      
        _INITIALIZATION(`Gdk::Rectangle&amp;',`GdkRectangle', `$3 =
        Glib::wrap(&amp;($4))')
      
        _INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 =
        ($1)($4)')
      
        _INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 =
        (SizeRequestMode)($4)')
      
        _WRAP_CTOR(ToolButton(Widget&amp; icon_widget, const Glib::ustring&amp;
        label{?}), gtk_tool_button_new)
      
        _WRAP_METHOD(bool get_cell_rect(const TreeModel::Path&amp; path, const
        CellRenderer&amp; cell, Gdk::Rectangle&amp; rect{&gt;&gt;}) const,
        gtk_icon_view_get_cell_rect)
      
        _WRAP_METHOD(void get_request_mode(SizeRequestMode&amp; mode{OUT})
        const, gtk_widget_get_request_mode)
      
        _WRAP_METHOD(void set_device_events(Gdk::EventMask events{.}, const
        Glib::RefPtr&lt;const Gdk::Device&gt;&amp; device{.}),
        gtk_widget_set_device_events)
      
        _WRAP_METHOD(void set_device_events(Gdk::EventMask events{events},
        const Glib::RefPtr&lt;const Gdk::Device&gt;&amp; device{device}),
        gtk_widget_set_device_events)
      
        gboolean gtk_icon_view_get_cell_rect(GtkIconView* icon_view,
        GtkTreePath* path, GtkCellRenderer* cell, GdkRectangle* rect);
      
        void gtk_widget_set_device_events(GtkWidget* widget, GdkDevice* device,
        GdkEventMask events);
      
    ...
    button.signal_clicked().connect(sigc::ptr_fun(&amp;on_button_clicked));
    ...

  $ git clone git://git.gnome.org/mm-common
  $ cp -a mm-common/skeletonmm libsomethingmm

# ./configure
# make
# make install

#include &lt;gtkmm/bin.h&gt;
#include &lt;gtkmm/activatable.h&gt;
_DEFS(gtkmm,gtk)
_PINCLUDE(gtkmm/private/bin_p.h)

namespace Gtk
{

class Button
  : public Bin,
    public Activatable
{
  _CLASS_GTKOBJECT(Button,GtkButton,GTK_BUTTON,Gtk::Bin,GtkBin)
  _IMPLEMENTS_INTERFACE(Activatable)
public:

  _CTOR_DEFAULT
  explicit Button(const Glib::ustring&amp; label, bool mnemonic = false);

  _WRAP_METHOD(void set_label(const Glib::ustring&amp; label), gtk_button_set_label)

  ...

  _WRAP_SIGNAL(void clicked(), "clicked")

  ...

  _WRAP_PROPERTY("label", Glib::ustring)
};

} // namespace Gtk

#include &lt;gtkmm/button.h&gt;

class OverriddenButton : public Gtk::Button
{
protected:
    virtual void on_clicked();
}

void OverriddenButton::on_clicked()
{
    std::cout &lt;&lt; "Hello World" &lt;&lt; std::endl;

    // call the base class's version of the method:
    Gtk::Button::on_clicked();
}

#include &lt;gtkmm/button.h&gt;

void on_button_clicked()
{
    std::cout &lt;&lt; "Hello World" &lt;&lt; std::endl;
}

main()
{
    Gtk::Button button("Hello World");
    button.signal_clicked().connect(sigc::ptr_fun(&amp;on_button_clicked));
}

#include &lt;gtkmm/button.h&gt;
#include &lt;gtkmm/window.h&gt;
class Foo : public Gtk::Window
{
private:
  Gtk::Button theButton;
  // will be destroyed when the Foo object is destroyed
};

#include &lt;libalgo.h&gt;

int main(int, char**)
{
  algo_init();

  std::cout &lt;&lt; get_defs(SOME_TYPE_WIDGET)
            &lt;&lt; get_defs(SOME_TYPE_STUFF);
  return 0;
}

$ ./enum.pl /usr/include/gtk-3.0/gtk/*.h &gt; gtk_enums.defs

$ ./h2def.py /usr/include/gtk-3.0/gtk/*.h &gt; gtk_methods.defs

$ cd gtk/src
$ /usr/lib/glibmm-2.4/proc/gmmproc -I ../../tools/m4 --defs . button . ./../gtkmm

$ cd tools/extra_defs_gen
$ ./generate_extra_defs &gt; gtk_signals.defs

$ for f in $(find libsomethingmm -depth -name '*skeleton*'); do \
    d="${f%/*}"; b="${f##*/}"; mv "$f" "$d/${b//skeleton/libsomething}"; \
  done

&gt; gdb with_signal
(gdb) catch throw
Catchpoint 1 (throw)
(gdb) run
Catchpoint 1 (exception thrown), 0x00714ff0 in __cxa_throw ()
(gdb) backtrace
#0  0x00714ff0 in __cxa_throw () from /usr/lib/i386-linux-gnu/libstdc++.so.6
#1  0x08048bd4 in throwSomething () at with_signal.cc:6
(gdb) continue
Continuing.
(with_signal:2375): glibmm-ERROR **
unhandled exception (type unknown) in signal handler

Program received signal SIGTRAP, Trace/breakpoint trap.

&gt; gdb with_signal
(gdb) run
(with_signal:2703): glibmm-ERROR **:
unhandled exception (type unknown) in signal handler

Program received signal SIGTRAP, Trace/breakpoint trap.
(gdb) backtrace
#2  0x0063c6ab in glibmm_unexpected_exception () at exceptionhandler.cc:77
#3  Glib::exception_handlers_invoke () at exceptionhandler.cc:150
#4  0x0063d370 in glibmm_source_callback (data=0x804d620) at main.cc:212
#13 0x002e1b31 in Gtk::Application::run (this=0x804f300) at application.cc:178
#14 0x08048ccc in main (argc=1, argv=0xbfffecd4) at with_signal.cc:16

&gt; gdb without_signal
(gdb) run
terminate called after throwing an instance of 'char const*'

Program received signal SIGABRT, Aborted.
(gdb) backtrace
#7  0x08048864 in throwSomething () at without_signal.cc:6
#8  0x0804887d in main (argc=1, argv=0xbfffecd4) at without_signal.cc:12

(gdb) catch throw
(gdb) commands
(gdb)   backtrace
(gdb)   continue
(gdb)   end
(gdb) set pagination off
(gdb) run

// _MEMBER_GET_PTR(engine_lang, lang_engine, EngineLang*, PangoEngineLang*)
// It's just a comment. It's difficult to find a real-world example.

// in a class that inherits from Gtk::Window...
Glib::RefPtr&lt;PrintOperation&gt; op = PrintOperation::create();
// ...set up op...
op-&gt;run(Gtk::PRINT_OPERATION_ACTION_PREVIEW, *this);

// in class ExampleWindow's method...
Glib::RefPtr&lt;PrintOperation&gt; op = PrintOperation::create();
// ...set up op...
op-&gt;signal_done().connect(sigc::bind(sigc::mem_fun(*this, &amp;ExampleWindow::on_printoperation_done), op));
// run the op

// with_signal.cc
#include &lt;gtkmm.h&gt;

bool throwSomething()
{
  throw "Something";
  return true;
}

int main(int argc, char** argv)
{
  Glib::signal_timeout().connect(sigc::ptr_fun(throwSomething), 500);
  Glib::RefPtr&lt;Gtk::Application&gt; app =
    Gtk::Application::create(argc, argv, "org.gtkmm.with_signal");
  app-&gt;hold();
  return app-&gt;run();
}

// without_signal.cc
#include &lt;gtkmm.h&gt;

bool throwSomething()
{
  throw "Something";
  return true;
}

int main(int argc, char** argv)
{
  throwSomething();
  Glib::RefPtr&lt;Gtk::Application&gt; app =
    Gtk::Application::create(argc, argv, "org.gtkmm.without_signal");
  return app-&gt;run();
}

//Within a class that inherits from Gtk::Window and keeps m_refPageSetup and m_refSettings as members...
Glib::RefPtr&lt;Gtk::PageSetup&gt; new_page_setup = Gtk::run_page_setup_dialog(*this, m_refPageSetup, m_refSettings);
m_refPageSetup = new_page_setup;

Button::Button(const Glib::ustring&amp; label, bool mnemonic)
:
  _CONSTRUCT("label", label.c_str(), "use_underline", gboolean(mnemonic))
{}

DerivedDialog* pDialog = 0;
builder-&gt;get_widget_derived("DialogBasic", pDialog);

DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder)
: Gtk::Dialog(cobject)
{
}

DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder)
: Gtk::Dialog(cobject),
  m_builder(builder),
  m_pButton(0)
{
  //Get the Glade-instantiated Button, and connect a signal handler:
  m_builder-&gt;get_widget("quit_button", m_pButton);
  if(m_pButton)
  {
    m_pButton-&gt;signal_clicked().connect( sigc::mem_fun(*this, &amp;DerivedDialog::on_button_quit) );
  }
}

Glib::RefPtr&lt;Gdk::Pixbuf&gt; pixbuf = Gdk::Pixbuf::create_from_file(filename);

Glib::RefPtr&lt;Gdk::Pixbuf&gt; pixbuf2 = pixbuf;

Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
Gdk::Pixbuf&amp; underlying = *refPixbuf; //Syntax error - will not compile.

Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf2 = refPixbuf;

Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
int width = refPixbuf-&gt;get_width();

Glib::RefPtr&lt;Gtk::Builder&gt; builder = Gtk::Builder::create_from_file("basic.glade");

Glib::RefPtr&lt;Gtk::Builder&gt; builder = Gtk::Builder::create_from_file("basic.glade", "treeview_products");

Glib::RefPtr&lt;Gtk::PrintOperation&gt; op = Gtk::PrintOperation::create();
// ...set up op...
op-&gt;set_export_filename("test.pdf");
Gtk::PrintOperationResult res = op-&gt;run(Gtk::PRINT_OPERATION_ACTION_EXPORT);

Glib::RefPtr&lt;Gtk::TreeModel&gt; refModel = m_TreeView.get_model();
if(refModel)
{
  int cols_count = refModel-&gt;get_n_columns();
  ...
}

Glib::RefPtr&lt;Gtk::TreeStore&gt; refStore =
Glib::RefPtr&lt;Gtk::TreeStore&gt;::cast_dynamic(refModel);
Glib::RefPtr&lt;Gtk::TreeStore&gt; refStore2 =
Glib::RefPtr&lt;Gtk::TreeStore&gt;::cast_static(refModel);

Glib::RefPtr&lt;Gtk::TreeStore&gt; refStore = Gtk::TreeStore::create(columns);
Glib::RefPtr&lt;Gtk::TreeModel&gt; refModel = refStore;

Glib::SignalProxy1&lt;bool, Gtk::DirectionType&gt; signal_focus()

Glib::SignalProxy3&lt;void, const TextBuffer::iterator&amp;, const Glib::ustrin&amp;, int&gt; signal_insert();

Gtk::Button* button = new Gtk::Button("example");
gtk_button_do_something_new(button-&gt;gobj());

Gtk::Button* pButton = new Gtk::Button("Test");

// do something useful with pButton

delete pButton;

Gtk::Dialog* pDialog = 0;
builder-&gt;get_widget("DialogBasic", pDialog);

Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton(icon, "Big"));
button-&gt;set_tooltip_text("Big Brush);
group_brushes-&gt;insert(*button);

Gtk::ToolItemGroup* group_brushes =
  Gtk::manage(new Gtk::ToolItemGroup("Brushes"));
m_ToolPalette.add(*group_brushes);

Gtk::Widget* CustomPrintOperation::on_create_custom_widget()
{
  set_custom_tab_label("My custom tab");

  Gtk::Box* hbox = new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 8);
  hbox-&gt;set_border_width(6);

  Gtk::Label* label = Gtk::manage(new Gtk::Label("Enter some text: "));
  hbox-&gt;pack_start(*label, false, false);
  label-&gt;show();

  hbox-&gt;pack_start(m_Entry, false, false);
  m_Entry.show();

  return hbox;
}

void CustomPrintOperation::on_custom_widget_apply(Gtk::Widget* /* widget */)
{
  Glib::ustring user_input = m_Entry.get_text();
  //...
}

GtkButton* cbutton = get_a_button();
Gtk::Button* button = Glib::wrap(cbutton);

GtkWidget* example_widget_new(int something, const char* thing)
{
        ExampleWidget* widget;
        widget = g_object_new (EXAMPLE_TYPE_WIDGET, NULL);
        example_widget_construct(widget, "something", something, "thing", thing);
}

void example_widget_construct(ExampleWidget* widget, int something, const char* thing)
{
        //Do stuff that uses private API:
        widget-&gt;priv-&gt;thing = thing;
        do_something(something);
}

GtkWidget* example_widget_new(int something, const char* thing)
{
        return g_object_new (EXAMPLE_TYPE_WIDGET, "something", something, "thing", thing, NULL);
}

MyContainer::MyContainer()
{
  Gtk::Button* pButton = Gtk::manage(new Gtk::Button("Test"));
  add(*pButton); //add *pButton to MyContainer
}

_CLASS_BOXEDTYPE(RGBA, GdkRGBA, NONE, gdk_rgba_copy, gdk_rgba_free)

_CLASS_BOXEDTYPE_STATIC(Rectangle, GdkRectangle)

_CLASS_GENERIC(AttrIter, PangoAttrIterator)

_CLASS_GOBJECT(AccelGroup, GtkAccelGroup, GTK_ACCEL_GROUP, Glib::Object, GObject)

_CLASS_GTKOBJECT(Button, GtkButton, GTK_BUTTON, Gtk::Bin, GtkBin)

_CLASS_INTERFACE(CellEditable, GtkCellEditable, GTK_CELL_EDITABLE, GtkCellEditableIface)

_CLASS_INTERFACE(LoadableIcon, GLoadableIcon, G_LOADABLE_ICON, GLoadableIconIface, Icon, GIcon)

_CLASS_OPAQUE_COPYABLE(Checksum, GChecksum, NONE, g_checksum_copy, g_checksum_free)

_CLASS_OPAQUE_REFCOUNTED(Coverage, PangoCoverage, pango_coverage_new, pango_coverage_ref, pango_coverage_unref)

_CONVERSION(`GtkTreeView*',`TreeView*',`Glib::wrap($3)')

_CONVERSION(`PrintSettings&amp;',`GtkPrintSettings*',__FR2P)
_CONVERSION(`const PrintSettings&amp;',`GtkPrintSettings*',__FCR2P)
_CONVERSION(`const Glib::RefPtr&lt;Printer&gt;&amp;',`GtkPrinter*',__CONVERT_REFPTR_TO_P($3))

_IGNORE(gtk_button_box_set_spacing, gtk_button_box_get_spacing)

_IMPLEMENTS_INTERFACE(Activatable)

_INITIALIZATION(`Gtk::Widget&amp;',`GtkWidget*',`$3 = Glib::wrap($4)')

_MEMBER_GET_GOBJECT(layout, layout, Pango::Layout, PangoLayout*)

_WRAP_ENUM(IconLookupFlags, GtkIconLookupFlags, NO_GTYPE)

_WRAP_ENUM(WindowType, GtkWindowType)

_WRAP_GERROR(PixbufError, GdkPixbufError, GDK_PIXBUF_ERROR)

_WRAP_METHOD(void set_text(const Glib::ustring&amp; text), gtk_entry_set_text)

_WRAP_METHOD_DOCS_ONLY(gtk_container_remove)

_WRAP_PROPERTY("label", Glib::ustring)

_WRAP_SIGNAL(void clicked(),"clicked")

_WRAP_VFUNC(SizeRequestMode get_request_mode() const, get_request_mode)

bool MyCallback() { std::cout &lt;&lt; "Hello World!\n" &lt;&lt; std::endl; return true; }

bool idleFunc();

bool input_callback(Glib::IOCondition condition);

bool on_button_press(GdkEventButton* event);
Gtk::Button button("label");
button.signal_button_press_event().connect( sigc::ptr_fun(&amp;on_button_press) );

bool on_key_press_or_release_event(GdkEventKey* event)
{
  if (event-&gt;type == GDK_KEY_PRESS &amp;&amp;
    event-&gt;keyval == GDK_KEY_1 &amp;&amp;
    (event-&gt;state &amp; (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK)) == GDK_MOD1_MASK)
  {
    handle_alt_1_press(); // GDK_MOD1_MASK is normally the Alt key
    return true;
  }
  return false;
}

Gtk::Entry m_entry; // in a class definition

// in the class constructor
m_entry.signal_key_press_event().connect( sigc::ptr_fun(&amp;on_key_press_or_release_event) );
m_entry.signal_key_release_event().connect( sigc::ptr_fun(&amp;on_key_press_or_release_event) );
m_entry.add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);

button.signal_button_press_event().connect( sigc::ptr_fun(&amp;on_mywindow_button_press), false );

class Server
{
public:
  //signal accessor:
  typedef sigc::signal&lt;void, bool, int&gt; type_signal_something;
  type_signal_something signal_something();

protected:
  type_signal_something m_signal_something;
};

Server::type_signal_something Server::signal_something()
{
  return m_signal_something;
}

class TextMark : public Glib::Object
{
  _CLASS_GOBJECT(TextMark, GtkTextMark, GTK_TEXT_MARK, Glib::Object, GObject)

protected:
  _WRAP_CTOR(TextMark(const Glib::ustring&amp; name, bool left_gravity = true), gtk_text_mark_new)

public:
  _WRAP_CREATE(const Glib::ustring&amp; name, bool left_gravity = true)

example-widget.h:56: error: using typedef-name 'ExampleWidget' after 'struct'
../../libexample/libexamplemm/example-widget.h:34: error: 'ExampleWidget' has a previous declaration here
make[4]: *** [example-widget.lo] Error 1

example-widget.h:60: error: '_ExampleWidget ExampleWidget' redeclared as different kind of symbol
../../libexample/libexamplemm/example-widget.h:34: error: previous declaration of 'typedef struct _ExampleWidget ExampleWidget'

int width = 0;
if(pixbuf)
{
  width = pixbuf-&gt;get_width();
}

m_button1.signal_clicked().connect( sigc::bind&lt;Glib::ustring&gt;( sigc::mem_fun(*this, &amp;HelloWorld::on_button_clicked), "button 1") );

my_connection.disconnect();

server.signal_something().connect(
  sigc::mem_fun(client, &amp;Client::on_server_something) );

sigc::connection  Glib::SignalIdle::connect(const sigc::slot&lt;bool&gt;&amp; slot,
                                    int priority = Glib::PRIORITY_DEFAULT_IDLE);

sigc::connection Glib::SignalIO::connect(const sigc::slot&lt;bool,Glib::IOCondition&gt;&amp; slot,
                                 int fd, Glib::IOCondition condition,
                                 int priority = Glib::PRIORITY_DEFAULT);

sigc::connection Glib::SignalTimeout::connect(const sigc::slot&lt;bool&gt;&amp; slot,
                                      unsigned int interval, int priority = Glib::PRIORITY_DEFAULT);

sigc::signal&lt;void, bool, int&gt; signal_something;

sigc::signal&lt;void,int&gt;::iterator signal&lt;void,int&gt;::connect( const sigc::slot&lt;void,int&gt;&amp; );

std::list&lt; Glib::RefPtr&lt;Gdk::Pixbuf&gt; &gt; listPixbufs;
Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
listPixbufs.push_back(refPixbuf);

typedef struct _ExampleWidget ExampleWidget;

struct _ExampleWidget
{
  ...
};

virtual void on_button_clicked(Glib::ustring data);

void ExampleWindow::on_printoperation_done(Gtk::PrintOperationResult result, const Glib::RefPtr&lt;PrintOperation&gt;&amp; op)
{
  if (result == Gtk::PRINT_OPERATION_RESULT_ERROR)
    //notify user
  else if (result == Gtk::PRINT_OPERATION_RESULT_APPLY)
    //Update PrintSettings with the ones used in this PrintOperation

  if (! op-&gt;is_finished())
    op-&gt;signal_status_changed().connect(sigc::bind(sigc::mem_fun(*this, &amp;ExampleWindow::on_printoperation_status_changed), op));
}

void ExampleWindow::on_printoperation_status_changed(const Glib::RefPtr&lt;PrintFormOperation&gt;&amp; op)
{
  if (op-&gt;is_finished())
    //the print job is finished
  else
    //get the status with get_status() or get_status_string()

  //update UI
}

void init()
{
  Gtk::Main::init_gtkmm_internals(); //Sets up the g type system and the Glib::wrap() table.
  wrap_init(); //Tells the Glib::wrap() table about the libsomethingmm classes.
}

void on_button_clicked();

class some_class
{
    void on_button_clicked();
};

some_class some_object;

main()
{
    Gtk::Button button;
    button.signal_clicked().connect( sigc::ptr_fun(&amp;on_button_clicked) );
    button.signal_clicked().connect( sigc::mem_fun(some_object, &amp;some_class::on_button_clicked) );
}

void on_insert(const TextBuffer::iterator&amp; pos, const Glib::ustring&amp; text, int bytes)

{
  Gtk::Button aButton;
  aButton.show();
  ...
  app-&gt;run();
}
Columnas «ocultas»# keep this file sorted alphabetically, one language code per line
de
ja#include &lt;gtkmm.h&gt;#m4 _CONVERSION(`GSList*',`std::vector&lt;Widget*&gt;',`Glib::SListHandler&lt;Widget*&gt;::slist_to_vector($3, Glib::OWNERSHIP_SHALLOW)')$ ./plug &amp;$ ./socket(Nota aparte: <application>GTK+</application> llama a este esquema «señalización»; el lector perspicaz con experiencia en kits de herramientas de IGU notará que este mismo diseño se ve a menudo bajo el nombre de «emisor-receptor» (por ejemplo, en la plataforma de Metrowerks PowerPlant para los Macintosh). Funciona casi de la misma manera: uno establece <literal>emisores</literal>, y después les conecta <literal>receptores</literal>; el emisor tiene una lista de los objetos que lo están recibiendo, y cuando alguien le envía un mensaje al emisor, llama a todos sus objetos en su lista con el mensaje. En <application>gtkmm</application>, los objetos de señales hacen de emisores, y los «slots» de receptores, o algo así. Se hablará de este tema más adelante).(Además, tendría los archivos <literal>ja.po</literal> y <literal>de.po</literal> en su carpeta <literal>po</literal> que contendrían las traducciones al alemán y al japonés, respectivamente)../docextract_to_xml.py -s ~/checkout/gnome/gtk+/gtk/ &gt; gtk_docs.xml
// creates its own adjustments
Gtk::TextView textview;
// uses the newly-created adjustment for the scrollbar as well
Gtk::Scrollbar vscrollbar (textview.get_vadjustment(), Gtk::ORIENTATION_VERTICAL);// note to translators: don't translate the "[noun]" part - it is
// just here to distinguish the string from another "jumps" string
text = strip(gettext("jumps[noun]"), "[noun]");//compiler error - no conversion from ustring to int.
int number = row[m_Columns.m_col_text];2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010<application>Gtk::Builder</application> verifica si el puntero es nulo y si el widget es del tipo esperado, y le advertirá en la línea de comandos de estos casos.<application>glibmm</application> proporciona el conjunto normal de funciones de lanzamiento de hilos, exclusión mutua, variables condicionales y clases de bloqueo de alcance requeridas para escribir programas de múltiples hilos usando C++.<application>gtkmm</application> 3 añadió algunas clases nuevas:<application>gtkmm</application> 3 también hizo varios cambios pequeños a la API, que probablemente encontrará cuando porte código que usaba <application>gtkmm</application>-2.4. Aquí hay una lista corta:La biblioteca de <application>gtkmm</application> 3 se llama <literal>libgtkmm-3.0</literal>, en vez de <literal>libgtkmm-2.4</literal> e instala sus archivos de cabecera en una carpeta versionada similarmente, por lo que su verificación pkg-config debería buscar <literal>gtkmm-3.0</literal> en vez de <literal>gtkmm-2.4</literal>.<application>gtkmm</application> le permite al programador controlar la vida (esto es, la construcción y la destrucción) de cualquier widget de la misma manera que cualquier otro objeto de C++. Esta flexibilidad le permite usar <literal>new</literal> y <literal>delete</literal> para crear y destruir objetos dinámicamente o para usar miembros de clase regulares (que se destruyen automáticamente cuando se destruye la clase) o usar instancias locales (que se destruyen cuando la instancia sale del alcance). Esta flexibilidad no está presente en algunos toolkits de IGU de C++, que sólo le permiten al programador usar un subconjunto de las características de gestión de memoria de C++.<application>gtkmm</application> le permite escribir código usando técnicas normales de C++ tales como encapsulación, derivación y polimorfismo. Como programador de C++, probablemente ya se habrá dado cuenta de que esto conlleva a un código más limpio y mejor organizado.<application>gtkmm</application> y Win32Las aplicaciones de <application>gtkmm</application> pueden soportar múltiples lenguajes fácilmente, incluyendo los no europeos como chino y los de derecha a izquierda como árabe. Una aplicación de <application>gtkmm</application> escrita apropiadamente y traducida usará el lenguaje apropiado en tiempo de ejecución basado en el entorno del usuario.Las aplicaciones <application>gtkmm</application> están compuestas por ventanas, estas a su vez contienen widgets, tales como botones y cuadros de texto. En algunos otros sistemas, los widgets se llaman «controles». Hay un objeto C++ en el código de la aplicación para cada widget contenido en las ventanas de una aplicación. Sólo debe llamar a un método de la clase widget para afectar al widget visible.<application>gtkmm</application> ordena los widgets jerárquicamente, usando <emphasis>contenedores</emphasis>. Un widget contenedor contiene a otros widgets. La mayoría de los widgets de <application>gtkmm</application> son contenedores. Las ventanas, las pestañas de los cuadernos y los botones son todos widgets contenedores. Hay dos formas de contenedores: de un sólo hijo, que descienden todos de <classname>Gtk::Bin</classname>, y de múltiples hijos, que descienden de <classname>Gtk::Container</classname>. La mayoría de los widgets en <application>gtkmm</application> descienden de <classname>Gtk::Bin</classname>, incluyendo <classname>Gtk::Window</classname>.Las clases de <application>gtkmm</application> se diseñaron con los reemplazos en mente; contienen métodos miembro virtuales específicamente pensados para reemplazarse.<application>gtkmm</application> comparado con Qt<application>gtkmm</application> actualmente funciona con el <ulink url="http://mingw.org/">compilador MingW/GCC3.4</ulink> y Microsoft Visual C++ 2005 o posterior (incluyendo las ediciones disponibles gratuitamente o «express») en la plataforma Windows. Hay un <ulink url="ftp://ftp.gnome.org/pub/GNOME/binaries/win32/gtkmm">instalador</ulink> disponible para gtkmm en Microsoft Windows. Consulte <ulink url="http://live.gnome.org/gtkmm/MSWindows/">http://live.gnome.org/gtkmm/MSWindows</ulink> para ver instrucciones sobre su uso.<application>gtkmm</application> tiene varios widgets que pueden ajustarse visualmente usando el ratón o el teclado, como los widgets <classname>Range</classname> (descritos en la sección <link linkend="chapter-range-widgets">Widgets de rango</link>). También hay algunos widgets que muestran una parte ajustable de un área más grande, como el widget <classname>Viewport</classname>. Estos widgets tienen objetos <classname>Gtk::Adjustment</classname> que expresan esta parte común de sus API.<application>gtkmm</application> implica menos código en comparación con GTK+, el cual usa nombres de funciones prefijadas y muchos macros.<application>gtkmm</application> es un envoltorio de C++ para <ulink url="http://www.gtk.org/">GTK+</ulink>, una biblioteca usada para crear interfaces gráficas de usuario. Esta liberado bajo la licencia LGPL, para que pueda desarrollar software abierto, software gratuito o software comercial usando <application>gtkmm</application> sin comprar ninguna licencia.<application>gtkmm</application> es un envoltorio<application>gtkmm</application> es más seguro, por lo que el compilador puede detectar errores que sólo pudieran detectarse durante ejecución al usar C. Este uso de tipos específicos también hace la API más limpia debido a que puede ver qué tipos deberían usarse con sólo mirar la declaración de un método.<application>gtkmm</application> no es un kit de herramientas nativo de C++, pero si es un envoltorio C++ de un conjunto de herramientas de C. Esta separación de la interfaz e implementación tiene sus ventajas. Los desarrolladores de <application>gtkmm</application> pasan la mayor parte de su tiempo hablando sobre cómo <application>gtkmm</application> puede presentar una API lo mas clara posible, sin compromisos incómodos debido a oscuros detalles técnicos. Nosotros contribuimos un poco al código fuente subyacente de GTK+, pero también lo hacen los programadores de C, los programadores de Perl, los programadores de Python, etc. Por ello, GTK+ se beneficia de una base de usuarios de mayor proporción que el lenguaje de herramientas específicas; hay más desarrolladores, más personas que prueban software en desarrollo, y más usuarios.<application>gtkmm</application> le hace fácil derivar widgets nuevos heredando de una clase de widget existente, derivando de un contenedor y añadiéndole widgets hijos, o derivando de un widget de un sólo elemento y cambiando su comportamiento. Pero ocasionalmente puede encontrar que no exista ningún punto de partida adecuado. En este caso, puede implementar un widget desde cero.<application>gtkmm</application> proporciona una manera fácil de gestionar documentos usados recientemente. Las clases involucradas en la implementación de esta funcionalidad son <classname>RecentManager</classname>, <classname>RecentChooserDialog</classname>, <classname>RecentChooserMenu</classname>, <classname>RecentChooserWidget</classname>, <classname>RecentAction</classname>, y <classname>RecentFilter</classname>.<application>gtkmm</application> proporciona cuatro tipos básicos de botones:<application>gtkmm</application> proporciona la función <function>manage()</function> y métodos <methodname>add()</methodname> para crear y destruir widgets. Cada widget, excepto una ventana de nivel superior, debe añadirse o empaquetarse en un contenedor para mostrarse. La función <function>manage()</function> marca un widget para que, cuando se añada a un contenedor, este se vuelva responsable de su eliminación.Los manejadores de señales de <application>gtkmm</application> son de «tipado fuerte», mientras que el código C de <application>GTK+</application> le permite conectar un retorno de llamada con el número y tipo incorrecto de argumentos, llevando a una violación de acceso en tiempo de ejecución. Y, a diferencia de <application>Qt</application>, <application>gtkmm</application> logra esto sin modificar el lenguaje C++.<application>gtkmm</application> usa la herramienta <command>gmmproc</command> para generar la mayor parte de su código fuente, usando archivos .defs que definen las API de las bibliotecas basadas en <classname>GObject</classname>. Es por esto que es bastante fácil crear envoltorios con el estilo de gtkmm adicionales de otras bibliotecas basadas en glib/GObject.<application>gtkmm</application> usa la biblioteca libsigc++ para implementar señales. Aquí hay una línea de código de ejemplo que conecta una señal «clicked» de Gtk::Button a un manejador de señales llamado «on_button_clicked»: <placeholder-1/><application>gtkmm</application> fue originalmente llamado gtk-- debido a que GTK+ ya tenía el signo + en el nombre. Sin embargo, debido a que -- no puede ser indexado fácilmente en los motores de búsqueda, el paquete fue generalmente llamado <application>gtkmm</application>, y eso fue con lo que nos quedamos.Las clases de widgets de <application>gtkmm</application> tienen métodos de acceso a señales, como <methodname>Gtk::Button::signal_clicked()</methodname>, que le permiten conectar su manejador de señales. Gracias a la flexibilidad de <application>libsigc++</application>, la biblioteca de retornos de llamada usada por <application>gtkmm</application>, el manejador de señales puede ser casi cualquier tipo de función, pero probablemente quiera usar un método de clase. Entre los programadores de C de <application>GTK+</application>, estos manejadores de señales a menudo se llaman retornos de llamada.<application>gtkmm</application>, como la mayoría de kits de herramientas de la IGU, está <emphasis>dirigido por eventos</emphasis>. Cuando ocurre un evento, como la pulsación de un botón del ratón sobre un widget, éste emitirá la señal apropiada. Cada widget puede emitir un conjunto de señales diferente. Para hacer que la pulsación de un botón resulte en una acción, establecemos un <emphasis>manejador de señales</emphasis> para atrapar la señal «clicked» del botón.<application>gtkmm</application>-3.0 es una versión nueva de la API <application>gtkmm</application> que se instala en paralelo con la API <application>gtkmm</application>-2.4, más vieja. La última versión de la API <application>gtkmm</application>-2.4 fue <application>gtkmm</application> 2.24. <application>gtkmm</application> 3 no tiene diferencias fundamentales importantes con respecto a <application>gtkmm</application> 2, pero hace varios cambios pequeños que no fueron posibles mientras se mantenía la compatibilidad de los binarios. Si nunca ha usado la API <application>gtkmm</application>-2.4, entonces puede ignorar con seguridad este capítulo.El script <application>intltool</application> / <application>xgettext</application> extrae las cadenas y las pone en un archivo <filename>mypackage.pot</filename>. Los traductores de su aplicación crean sus traducciones primero copiando este archivo <filename>.pot</filename> a un archivo <filename>localename.po</filename>. Una localización identifica a un lenguaje y una codificación para ese lenguaje, incluyendo formatos de fecha y numéricos. Más tarde, cuando el texto en su código fuente haya cambiado, el script <literal>msmerge</literal> se usará para actualizar los archivos <filename>localename.po</filename> del archivo <filename>.pot</filename> regenerado.Las <classname>ButtonBox</classname> ayudan a hacer que las aplicaciones aparezcan consistentes porque usan opciones estándar, como espaciado entre botones y empaquetado.<classname>Gdk::Drawable</classname> se quitó, y sus métodos se movieron a <classname>Gdk::Window</classname>.<classname>Gdk::Pixmap</classname> y <classname>Gdk::Bitmap</classname> se eliminaron en favor de <classname>Gdk::Pixbuf</classname>.<classname>Gdk::RGBA</classname> reemplaza a <classname>Color</classname>, añadiendo un componente alfa para la opacidad. <classname>Colormap</classname> se eliminó, junto con su molesto uso para asignar colores.<classname>Glib::ListHandle&lt;Gtk::Widget*&gt;</classname>: usa <classname>std::vector&lt;Gtk::Widget*&gt;</classname>, <classname>std::list&lt;Gtk::Widget*&gt;</classname>, etc.<classname>Glib::SListHandle&lt;Gtk::Widget*&gt;</classname>: usa <classname>std::vector&lt;Gtk::Widget*&gt;</classname>, <classname>std::list&lt;Gtk::Widget*&gt;</classname>, etc.<classname>Glib::StringArrayHandle</classname> o <classname>Glib::ArrayHandle&lt;Glib::ustring&gt;</classname>: usan <classname>std::vector&lt;Glib::ustring&gt;</classname>, <classname>std::list&lt;Glib::ustring&gt;</classname>, <type>const char*[]</type>, etc.<classname>Gtk::Adjustment</classname>, <classname>IconSet</classname> y <classname>Gdk::Cursor</classname> se usan ahora a través de <classname>Glib::RefPtr</classname>.<classname>Gtk::AppChooser</classname>, <classname>Gtk::AppChooserButton</classname>, <classname>Gtk::AppChooserDialog</classname> permiten al usuario seleccionar una aplicación instalada para abrir un determinado tipo de contenido.<classname>Gtk::Box</classname> ordena a sus widgets hijos vertical u horizontalmente. Use <methodname>pack_start()</methodname> y <methodname>pack_end()</methodname> para insertar widgets hijos.<classname>Gtk::Box</classname>, <classname>Gtk::ButtonBox</classname>, <classname>Gtk::IconView</classname>, <classname>Gtk::Paned</classname>, <classname>Gtk::ProgressBar</classname>, <classname>Gtk::ScaleButton</classname>, <classname>Gtk::Scrollbar</classname> y <classname>Gtk::Separator</classname> ahora derivan de <classname>Gtk::Orientable</classname>, permitiendo especificar su orientación (vertical u horizontal) sin requerir el uso de una clase derivada como <classname>Gtk::HBox</classname>.<classname>Gtk::Builder</classname> debe usarse a través de <classname>Glib::RefPtr</classname>. Al igual que todos las clases similares, necesitará usar un método <methodname>create()</methodname> para instanciarla. Por ejemplo, <placeholder-1/> Esto instanciará las ventanas definidas en el archivo .glade, a pesar de que no se mostrarán inmediatamente a menos que lo haya especificado así mediante la ventana <guilabel>Propiedades</guilabel> en <application>Glade</application>. <classname>Gtk::Button</classname> también es un contenedor, por lo que puede poner otro widget, como un <classname>Gtk::Image</classname> dentro de él.<classname>Gtk::CellLayout</classname>, usada por <classname>Gtk::IconView</classname>, <classname>Gtk::TreeView::Column</classname> y <classname>Gtk::ComboBox</classname> ahora tiene una <classname>Gtk::CellArea</classname>, que puede usarse para especificar más detalles acerca de cómo las <classname>CellRenderer</classname> se ordenan y alinean.<classname>Gtk::CheckButton</classname> hereda de <classname>Gtk::ToggleButton</classname>. La única diferencia real entre ambos es la apariencia de <classname>Gtk::CheckButton</classname>. Puede verificar, establecer, y conmutar una casilla de verificación utilizando los mismos métodos miembro que para <classname>Gtk::ToggleButton</classname>.<classname>Gtk::Grid</classname> ordena sus widgets hijos en filas y columnas. Use <methodname>attach()</methodname>, <methodname>attach_next_to()</methodname> y <methodname>add()</methodname> para insertar widgets hijos.<classname>Gtk::Grid</classname> es un widget contenedor nuevo que eventualmente reemplazará a <classname>Gtk::Box</classname> y a <classname>Gtk::Table</classname>. Ordena a sus hijos de acuerdo a sus propiedades en lugar de sus propios detalles de disposición.<classname>Gtk::IconView</classname>, <classname>Gtk::TextView</classname>, <classname>Gtk::TreeView</classname> y otros widgets derivan de Scrollable en vez de tener sus propios métodos como <methodname>get_vadjustment()</methodname> y su propia señal set_scroll_adjustments.<classname>Gtk::Scale</classname> y <classname>Gtk::Scrollbar</classname> heredan de <classname>Gtk::Range</classname> y comparten mucha funcionalidad. Contienen un «canal» y un «control deslizante» (a veces llamado «rueda» en otros entornos IGU). Deslizar el control con el puntero lo mueve dentro del canal, mientras que pulsar en el canal avanza al control deslizante hacia la ubicación de la pulsación, completamente o en una cantidad definida dependiendo del botón que se use. Este es el comportamiento normal de las barras de desplazamiento.Los widgets <classname>Gtk::Scale</classname> (o «deslizadores») le permiten al usuario seleccionar y manipular visualmente un valor dentro de un rango específico. Puede usar uno, por ejemplo, para ajustar el nivel de ampliación en una previsualización de una imagen, o para controlar el brillo de un color, o especificar la cantidad de minutos de inactividad antes de que aparezca un salvapantallas.<classname>Gtk::Style</classname> y <classname>Gtk::Rc</classname> se quitaron y se reemplazaron por <classname>Gtk::StyleContext</classname>, y <classname>Gtk::StyleProvider</classname>, así como <classname>Gtk::CssProvider</classname>.<classname>Gtk::Switch</classname> muestra los estados Encendido/Apagado más explícitamente que <classname>Gtk::CheckBox</classname>. Puede ser útil, por ejemplo, al permitir a los usuarios activar hardware.<classname>Gtk::Table</classname> permite poner widgets en una cuadrícula, de manera similar a <classname>Gtk::Grid</classname>.<classname>Gtk::Table</classname> se marcó como obsoleto en <application>gtkmm</application> 3.4 y no se debe usar en el código nuevo. Use <classname>Gtk::Grid</classname> en su lugar.Los objetos <classname>Gtk::TargetEntry</classname> contienen esta información: <placeholder-1/><classname>Gtk::TextBuffer</classname> es el modelo que contiene los datos del <classname>Gtk::TextView</classname>, al igual que el <classname>Gtk::TreeModel</classname> usado por <classname>Gtk::TreeView</classname>. Esto permite a dos o más <classname>Gtk::TreeView</classname> compartir el mismo <classname>TextBuffer</classname>, y permite mostrar esos búferes de texto de una manera ligeramente diferente. O bien, puede mantener varios <classname>Gtk::TextBuffer</classname> y elegir mostrar cada uno en distintas ocasiones en el mismo widget <classname>GtK::TextView</classname>.<classname>Gtk::TextView</classname> tiene varios métodos <methodname>scroll_to_*()</methodname>. Estos le permiten asegurarse de que una parte particular del búfer de texto es visible. Por ejemplo, la característica «Encontrar» de su aplicación podría usar <methodname>Gtk::TextView::scroll_to_iter()</methodname> para mostrar el texto encontrado.<classname>Gtk::ToggleButton</classname> es más útil como clase base para las clases <classname>Gtk::CheckButton</classname> y <classname>Gtk::RadioButton</classname>.Entonces podrá añadir varios <classname>Gtk::ToolItem</classname> al grupo. Por ejemplo, así:<classname>Gtk::TreeModel</classname> proporciona un contenedor de sus hijos al estilo de las bibliotecas C++ estándar, a través del método <methodname>children()</methodname>. Puede usar los incrementos del iterador familiares de los métodos <methodname>begin()</methodname> y <methodname>end()</methodname>.Los modelos <classname>Gtk::TreeStore</classname> pueden tener elementos hijos. Añádalos con los métodos <methodname>append()</methodname>, <methodname>prepend()</methodname>, o <methodname>insert()</methodname>, así:<classname>Gtk::TreeView</classname> ya implementa un simple «arrastrar y soltar» cuando se usa con los modelos <classname>Gtk::ListStore</classname> o <classname>Gtk::TreeStore</classname>. Si es necesario, también le permite implementar un comportamiento más complejo cuando se arrastran y sueltan los elementos, usando la API de <link linkend="chapter-draganddrop">Arrastrar y soltar</link> normal.<classname>Gtk::Widget</classname> tiene varios métodos y señales cuyo prefijo es «drag_». Se usan para arrastrar y soltar.Normalmente, simplemente se añaden los <classname>Menus</classname> a la ventana, pero también pueden mostrarse temporalmente como resultado de una pulsación del botón del ratón. Por ejemplo, se puede mostrar un menú contextual cuando el usuario pulsa el botón derecho de su ratón.<classname>MessageDialog</classname> es una clase de conveniencia, usada para crear diálogos de mensajes estándar y simples, con un mensaje, un icono, y botones para la respuesta del usuario. Puede especificar el tipo de mensaje y el texto en el constructor, así como los botones estándar a través de la enum <literal>Gtk::ButtonsType</literal>.Los <classname>RadioButtons</classname> están «apagados» cuando se crean; esto significa que cuando hace un grupo de ellos, primero estarán todos apagados. No olvide encender uno de ellos usando <methodname>set_active()</methodname>:Los widgets <classname>Range</classname> típicamente conectan un manejador a esta señal, que cambia su apariencia para reflejar el cambio: por ejemplo, el tamaño de un control deslizante en una barra de desplazamiento crecerá o se encogerá de manera inversamente proporcional a la diferencia entre los valores <parameter>lower</parameter> y <parameter>upper</parameter> de su <classname>Adjustment</classname>.<classname>RecentChooser</classname> es una interfaz que pueden implementar los widgets que muestran la lista de archivos usados recientemente. <application>gtkmm</application> proporciona cuatro implementaciones incorporadas para elegir archivos recientes: <classname>RecentChooserWidget</classname>, <classname>RecentChooserDialog</classname>, <classname>RecentChooserMenu</classname>, y <classname>RecentAction</classname>.<classname>RecentChooserMenu</classname> y <classname>RecentAction</classname> le permiten listar archivos usados recientemente en un menú.<classname>RecentChooserWidget</classname> es un widget simple para mostrar una lista de archivos usados recientemente. <classname>RecentChooserWidget</classname> es el bloque de construcción básico de <classname>RecentChooserDialog</classname>, pero puede empotrarlo en su interfaz de usuario si quiere.<classname>RecentManager</classname> actúa como una base de datos de archivos usados recientemente. Use esta clase para registrar archivos nuevos, eliminarlos o buscarlos. Hay una lista de archivos usados recientemente por cada usuario.<classname>RecentManager</classname> es el modelo de un patrón modelo-vista cuya vista es la clase que implementa la interfaz <classname>RecentChooser</classname>.Los widgets <classname>Scale</classname> pueden mostrar su valor actual como un número junto al canal. De manera predeterminada muestran el valor, pero puede cambiar esto con el método <methodname>set_draw_value()</methodname>.Los widgets <classname>ScrolledWindow</classname> crean un área desplazable. Puede insertar cualquier tipo de widget en una ventana <classname>ScrolledWindow</classname>, y será accesible sin importar su tamaño mediante el uso de barras de desplazamiento. Tenga en cuenta que <classname>ScrolledWindow</classname> no es un <classname>Gtk::Window</classname>, a pesar del nombre ligeramente confuso.Los <classname>SpinButton</classname> usan un objeto <link linkend="chapter-adjustment">Adjustment</link> para mantener la información del rango de valores. Los «SpinButton» usan estos atributos del «Adjustment» así: <placeholder-1/>Generalmente se invalidan los iteradores del <classname>TextBuffer</classname> cuando el texto cambia, pero puede usar una <classname>Gtk::TextBuffer::Mark</classname> para recordar una posición en estas situaciones. Por ejemplo,Los <classname>TextView</classname> tienen varios métodos que le permiten cambiar la presentación del búfer de esta vista particular. Algunos de estos pueden anularse por los <classname>Gtk::TextTag</classname> en el búfer, si especifican las mismas cosas. Por ejemplo, <methodname>set_left_margin()</methodname>, <methodname>set_right_margin()</methodname>, <methodname>set_indent()</methodname>, etc.Los <classname>ToggleButton</classname> son como los <classname>Button</classname> normales, pero cuando se pulsan quedan activados, o presionados, hasta que se vuelvan a pulsar.Los <classname>Widgets</classname> pueden identificarse como orígenes o destinos usando estos métodos de <classname>Gtk::Widget</classname>:<command>gmmproc</command> le advertirá en stdout de funciones y señales que haya olvidado envolver, ayudándole a asegurarse que está envolviendo la API completa. Pero si no quiere envolver algunas funciones o señales, o si elige escribir a mano algunos métodos entonces puede usar las macros _IGNORE() o _IGNORE_SIGNAL() para hacer que <command>gmmproc</command> deje de quejarse.<filename>libsomething</filename>: contiene el archivo de cabecera principal y el archivo .pc de pkg-config.<filename>libsomethingmm</filename>: contiene los archivos .h y .cc generados y escritos a mano.<filename>libsomethingmm</filename>: la carpeta de nivel superior.<filename>private</filename>: contiene los archivos <filename>*_p.h</filename> generados.<filename>src</filename>: contiene los archivos de fuentes .hg y .ccg.<function>_WRAP_METHOD()</function> también soporta establecer parámetros de salida de C++ desde parámetros de salida de C si la función de C que está envolviendo los tiene. Suponga, por ejemplo, que quiere envolver la siguiente función de C que devuelve un valor en su parámetro de salida de C <parameter>rect</parameter>: <placeholder-1/> Para hacer que <command>gmmproc</command> ponga el valor devuelto en el parámetro de salida de C++ <parameter>rect</parameter> una vez que la función de C retorna, se puede usar algo como la siguiente directiva de <function>WRAP_METHOD()</function>: <placeholder-2/> El <literal>{&gt;&gt;}</literal> que sigue al nombre del parámetro <parameter>rect</parameter> indica que el parámetro de salida de C++ debe establecerse a partir del valor devuelto por el parámetro de C desde la función de C. <command>gmmproc</command> generará una declaración de una variable temporal en la que se almacenará el valor del parámetro de salida de C y una declaración que establece el parámetro de salida de C++ desde la variable temporal. En este caso puede ser necesario tener una <function>_INITIALIZATION()</function> que describa cómo establecer un <classname>Gdk::Rectangle&amp;</classname> desde un <classname>GdkRectangle*</classname> como la siguiente: <placeholder-3/><function>_WRAP_METHOD()</function>, <function>_WRAP_SIGNAL()</function>, y <function>_WRAP_PROPERTY()</function><function>sigc::bind()</function> no se usa comúnmente, pero a veces la encontrará útil. Si está familiarizado con programación en <application>GTK+</application>, entonces probablemente ya haya notado que esto es similar a los argumentos <literal>gpointer data</literal> adicionales que todos los retornos de llamada de GTK+ tienen. Generalmente se abusa de esto en <application>GTK+</application> para pasar información que debe almacenarse como datos miembros en un widget derivado, pero la derivación de widgets es muy difícil en C. Hay mucha menos necesidad de este «hack» en <application>gtkmm</application>.<function>sigc::ptr_fun()</function> genera un <classname>sigc::slot</classname>. Un «slot» es un objeto que se comporta como una función, pero en realidad es un objeto. Estos también se llaman objetos función, o funtores. <function>sigc::ptr_fun()</function> genera un «slot» para una función independiente o un método estático. <function>sigc::mem_fun()</function> genera un «slot» para un método miembro de una instancia particular.<literal>$3</literal> se reemplazará por el nombre del parámetro de salida del método de C++ y <literal>$4</literal> se reemplazará por el valor de retorno de la función de C cuando gmmproc use esta inicialización. Por conveniencia, <literal>$1</literal> también se reemplazará por el tipo de C++ sin el «et» (&amp;) y <literal>$2</literal> se reemplazará por el tipo de C.<literal>$3</literal> se reemplazará por el nombre del parámetro cuando gmmproc use esta conversión.<literal>Gtk::PACK_EXPAND_PADDING</literal>: se rellena espacio adicional. Los widgets se espacian de manera similar, pero sus tamaños no cambiarán: en su lugar, habrá espacio vacío.<literal>Gtk::PACK_EXPAND_WIDGET</literal>: se usa espacio adicional incrementando el tamaño del widget hijo, sin cambiar la cantidad de espacio entre los widgets.<literal>Gtk::PACK_SHRINK</literal>: el espacio se contrae al tamaño del widget hijo. El widget usará el espacio justo y necesario, y nunca se expandirá.<literal>Gtk::UPDATE_CONTINUOUS</literal>: esta es la predeterminada. Se emite la señal <literal>value_changed</literal> continuamente, es decir, siempre que el deslizador se mueva aunque sea sólo un poco.<literal>Gtk::UPDATE_DELAYED</literal>: la señal <literal>value_changed</literal> se emite cuando el usuario suelta el botón del ratón, o si el deslizador deja de moverse por un corto período de tiempo.<literal>Gtk::UPDATE_DISCONTINUOUS</literal>: la señal <literal>value_changed</literal> sólo se emite una vez que el deslizador se detuvo y el usuario soltó el botón del ratón.<literal>LINGUAS</literal> contiene una lista ordenada alfabéticamente de códigos que identifican los idiomas a los que se traduce su programa (las líneas de comentarios que comienzan con <literal>#</literal> se ignoran). Cada código de idioma listado en el archivo <literal>LINGUAS</literal> debe tener un archivo <literal>.po</literal> correspondiente. Entonces, si su programa estuviera traducido al alemán y al japonés, su archivo <literal>LINGUAS</literal> se vería así:<literal>POTFILES.in</literal> es una lista de rutas a todos los archivos que contienen cadenas marcadas para traducción, comenzando desde la carpeta raíz del proyecto. Entonces, por ejemplo, si el código fuente de su proyecto estuviera en una subcarpeta llamda <literal>src</literal>, y si tuviera dos archivos conteniendo cadenas que deben traducirse, su archivo <literal>POTFILES.in</literal> se vería así:<literal>actions</literal> indica las acciones de arrastrar y soltar que este destino puede recibir: consulte la descripción arriba.<literal>actions</literal> es una combinación de valores complementarios, que especifican qué operaciones de arrastrar y soltar serán posibles desde este origen: por ejemplo, copiar, mover, o enlazar. El usuario puede elegir entre las acciones usando teclas modificadoras, como <keycap>Mayús</keycap> para cambiar de <literal>copiar</literal> a <literal>mover</literal>, y esto se mostrará con un cursor diferente.<literal>begin_print</literal>: debe manejar esta señal, porque aquí es donde crea y configura un <classname>Pango::Layout</classname> usando el <classname>Gtk::PrintContext</classname> proporcionado y divide la salida de impresión en páginas.<literal>done</literal>: esta señal se emite cuando termina la impresión, indicando que se han almacenado en el búfer los datos. Tenga en cuenta que el <literal>Gtk::PrintOperationResult</literal> proporcionado podría indicar un error. En cualquier caso, probablemente quiera notificar al usuario el estado final.<literal>drag_begin</literal>: proporciona DragContext.<literal>drag_delete</literal>: le da al origen la oportunidad de eliminar los datos originales si es lo apropiado.<literal>drag_data_get</literal>: proporciona <literal>info</literal> acerca del formato de datos arrastrado, y una estructura <literal>Gtk::SelectionData</literal>, en la que debe poner los datos pedidos.<literal>drag_data_received</literal>: proporciona <literal>info</literal> acerca del formato de datos arrastrado, y una estructura <literal>Gtk::SelectionData</literal> que contiene los datos soltados. Debe llamar al método <methodname>drag_finish()</methodname> del <literal>DragContext</literal> para indicar si la operación tuvo éxito.<literal>drag_drop</literal>: proporciona DragContext y coordenadas.<literal>drag_end</literal>: proporciona DragContext.<literal>drag_motion</literal>: proporciona DragContext y coordenadas. Puede llamar al método drag_status() del DragContext para indicar qué objetivo se aceptará.<literal>draw_page</literal>: debe manejar esta señal, que proporciona un <classname>PrintContext</classname> y un número de página. El <classname>PrintContext</classname> debe usarse para crear un <classname>Cairo::Context</classname> en el que la página proporcionada debe dibujarse. Para procesar texto, itere sobre el <classname>Pango::Layout</classname> que creó en el manejador <literal>begin_print</literal>.<literal>end_print</literal>: su manejador es un lugar seguro para liberar cualquier recurso relacionado con una <classname>PrintOperation</classname>. Si tiene una clase personalizada que herede de <classname>PrintOperation</classname>, es naturalmente más simple hacerlo en el destructor.<literal>flags</literal> es una combinación de valores complementarios que indica cómo responderá el widget visualmente a los objetos que se arrastran y sueltan.<literal>lower</literal>: valor mínimo del rango<literal>page_increment</literal>: valor en el que se incrementa/decrementa cuando se presiona un botón con el botón 2 del ratón<literal>page_size</literal>: no se usa<literal>paginate</literal>: la paginación es potencialmente lenta, por lo que, si necesita monitorizarla puede llamar al método <methodname>PrintOperation::set_show_progress()</methodname> y manejar esta señal.<literal>request_page_setup</literal>: proporciona un <classname>PrintContext</classname>, número de página y <classname>Gtk::PageSetup</classname>. Maneje esta señal si necesita modificar la configuración de cada página.<literal>start_button_mask</literal> es una combinación de valores complementarios, que especifica qué tecla modificadora o botón del ratón debe presionarse para empezar a arrastrar.<literal>status_changed</literal>: emitida siempre que el estado de un trabajo de impresión cambia, hasta que termina. Llame al método <methodname>PrintOperation::set_track_print_status()</methodname> para monitorizar el estado del trabajo luego de haberlo almacenado en el búfer. Para ver el estado, use <methodname>get_status()</methodname> o <methodname>get_status_string()</methodname>.<literal>step_increment</literal>: valor en el que se incrementa/decrementa cuando se presiona un botón con el botón 1 del ratón<literal>upper</literal>: valor máximo del rango<literal>value</literal>: valor del «SpinButton»<methodname>Gtk::Widget::show()</methodname> le permite a <application>gtkmm</application> saber que se han terminado de establecer los atributos del widget, y que está listo para mostrarse. Puede usar <methodname>Gtk::Widget::hide()</methodname> para hacerlo desaparecer de nuevo. El orden en el que muestra los widgets no es importante, pero se le sugiere mostrar la ventana de nivel superior al final; de esta manera, toda la ventana aparecerá con su contenido ya dibujado. De lo contrario, el usuario verá primero una ventana vacía, en la que los widgets se dibujarán gradualmente.<methodname>child_type_vfunc()</methodname>: devuelve qué tipo de hijo puede añadirse.<methodname>forall_vfunc()</methodname>: llama al mismo retorno de llamada para cada uno de los hijos.<methodname>get_preferred_height_for_width_vfunc()</methodname>: calcula la altura mínima y natural del contenedor, si se le da la anchura especificada.<methodname>get_preferred_height_for_width_vfunc()</methodname>: calcula la altura mínima y natural del widget, si se le da la anchura especificada.<methodname>get_preferred_height_vfunc()</methodname>: calcula la altura mínima y natural del contenedor.<methodname>get_preferred_height_vfunc()</methodname>: calcula la altura mínima y natural del widget.<methodname>get_preferred_width_for_height_vfunc()</methodname>: calcula la anchura mínima y natural del contenedor, si se le da la altura especificada.<methodname>get_preferred_width_for_height_vfunc()</methodname>: calcula la anchura mínima y natural del widget, si se le da la altura especificada.<methodname>get_preferred_width_vfunc()</methodname>: calcula la anchura mínima y natural del contenedor.<methodname>get_preferred_width_vfunc()</methodname>: calcula la anchura mínima y natural del widget.<methodname>get_request_mode_vfunc()</methodname>: (opcional) devuelve qué <literal>Gtk::SizeRequestMode</literal> prefiere el widget.<methodname>get_request_mode_vfunc()</methodname>: devuelve qué <literal>Gtk::SizeRequestMode</literal> prefiere el contenedor.<methodname>get_widget()</methodname> devuelve widgets hijos que gestiona <function>manage()</function> (consulte el capítulo <link linkend="chapter-memory">Gestión de memoria</link>), por lo que se eliminarán cuando se elimine su contenedor padre. Por lo tanto, si sólo obtiene un widget hijo de <application>Gtk::Builder</application>, en lugar de la ventana completa, debe ponerlo en un <classname>Container</classname> o bien eliminarlo. Las <classname>Windows</classname> (como <classname>Dialogs</classname>) no pueden gestionarse porque no tienen contenedor padre, por lo que debe eliminarlas en algún momento.<methodname>on_add()</methodname>: añade un widget hijo al contenedor.<methodname>on_draw()</methodname>: dibuja en el <methodname>Cairo::Context</methodname> proporcionado.<methodname>on_map()</methodname>: (opcional)<methodname>on_realize()</methodname>: asocia una <methodname>Gdk::Window</methodname> al widget.<methodname>on_remove()</methodname>: elimina un widget hijo del contenedor.<methodname>on_size_allocate()</methodname> recibe la altura y anchura reales que el contenedor padre ha decidido darle a su widget. Esto podría ser más del mínimo, o aún más que el tamaño natural, por ejemplo si se ha expandido la ventana de nivel superior. Puede escoger ignorar el espacio adicional y dejar un área en blanco, expandir a sus widgets hijos para llenar el espacio, o bien expandir la separación entre sus widgets. Es su contenedor, por lo que es su decisión. No olvide llamar a <methodname>set_allocation()</methodname> dentro de su implementación de <methodname>on_size_allocate()</methodname> para usar realmente el espacio asignado que le ha ofrecido el contenedor padre.<methodname>on_size_allocate()</methodname>: posiciona a los widgets hijos de acuerdo a la altura y anchura que se le ha dado al contenedor.<methodname>on_size_allocate()</methodname>: posiciona al widget de acuerdo a la altura y anchura que se le ha dado.<methodname>on_unmap()</methodname>: (opcional)<methodname>on_unrealize()</methodname>: (opcional) rompe la asociación con la <methodname>Gdk::Window</methodname>.<methodname>run()</methodname> puede devolver <literal>PRINT_OPERATION_RESULT_IN_PROGRESS</literal>. Para rastrear el estado y manejar el resultado de un error, necesita implementar manejadores de las señales <literal>done</literal> y <literal>status_changed</literal>.<placeholder-1/> (o <placeholder-2/> para nombres de archivos)<placeholder-1/> Ahora, cuando los objetos del tipo <classname>MyContainer</classname> se destruyan, el botón también se eliminará. Ya no es necesario eliminar <varname>pButton</varname> para liberar su memoria; su eliminación se ha delegado al objeto <classname>MyContainer</classname>.<placeholder-1/> paquete de ejemplo<type>GdkEventButton</type> es una estructura que contiene los parámetros del evento, como las coordenadas del puntero del ratón en el momento en el que se presionó el botón. Hay varios tipos diferentes de estructuras <type>GdkEvent</type> para la variedad de eventos.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Button.html"><classname>Gtk::Button</classname></ulink>. Botones estándar, normalmente marcados con una etiqueta o imagen. Presionar uno desencadena una acción. Consulte la sección <link linkend="sec-pushbuttons">botón</link>.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1CheckButton.html"><classname>Gtk::CheckButton</classname></ulink>. Estos actúan como botones conmutadores, pero muestran su estado en pequeños cuadrados, con su etiqueta a un lado. Los puede usar en la mayoría de las situaciones que requieren una configuración de encendido/apagado. Consulte la sección<link linkend="sec-checkboxes">casilla de verificación</link>.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1RadioButton.html"><classname>Gtk::RadioButton</classname></ulink>. Su nombre proviene de los selectores de estación en las antiguas radios de coches. Estos botones se usan en grupos para opciones que se excluyen mutuamente. Pulsar uno de ellos hace que los otros botones de su grupo se apaguen. Son similares a las casillas de verificación (un pequeño widget con una etiqueta a un lado), pero normalmente se ven diferentes. Consulte la sección <link linkend="sec-radio-buttons">botón de radio</link>.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToggleButton.html"><classname>Gtk::ToggleButton</classname></ulink>. A diferencia de un botón normal, que baja y sube en la misma pulsación, un botón conmutable se queda abajo hasta que lo vuelve a presionar. Puede ser útil como conmutador de encendido/apagado. Consulte la sección <link linkend="sec-toggle-buttons">botón conmutador</link>.<varname>app_exec</varname>: la línea de comandos que se usará para lanzar este recurso. La cadena puede contener los caracteres de escape «f» y «u» que se expandirán en la ruta del archivo de recursos y el URI respectivamente<varname>app_name</varname>: el nombre de la aplicación que registró el recurso<varname>description</varname>: una descripción corta del recurso en una cadena codificada en UTF-8<varname>display_name</varname>: el nombre del recurso que se mostrará como una cadena codificada en UTF-8<varname>groups</varname>: una lista de grupos asociada con este elemento. Los grupos son esencialmente cadenas arbitrarias asociadas con un recurso en particular. Puede pensar en ellos como «categorías» (como «correo-e», «gráficos», etc), o etiquetas del recurso<varname>is_private</varname>: determina si el recurso debe ser visible sólo a las aplicaciones que lo han registrado o no<varname>mime_type</varname>: el tipo MIME del recursoUn <classname>ComboBox</classname> puede contener un widget <classname>Entry</classname> para la entrada de texto arbitrario, mediante la especificación de <literal>true</literal> al parámetro <literal>has_entry</literal> del constructor.Un widget <classname>Entry</classname> puede ofrecer una lista desplegable de opciones pre-existentes sobre la base de los primeros caracteres escritos por el usuario. Por ejemplo, un cuadro de diálogo de búsqueda podría sugerir el texto de búsquedas anteriores.Se usa un <classname>Glib::Dispatcher</classname> para enviar notificaciones desde el hilo activo al hilo de la IGU. La clase <classname>ExampleWorker</classname> contiene datos a los que acceden ambos hilos. Estos datos están protegidos por una clase <classname>Glib::Threads::Mutex</classname>. Sólo el hilo de la IGU actualiza la propia IGU.Solo el hilo receptor o de trabajo pueden emitir in objeto <classname>Glib::Dispatcher</classname>, aunque que esto debe hacerse dentro de límites razonables. En sistemas similares a Unix, los objetos <classname>Glib::Dispatcher</classname> comparten un hilo común, que en teoría podría llenarse en un sistema muy cargado ejecutando un programa con un número muy alto de objetos <classname>Dispatcher</classname> en uso. Si la tubería se llenara antes de que el bucle principal del hilo tuviera la oportunidad de leerla para vaciarla, y el hilo receptor intentara emitir, es decir escribirle cuando está en esta condición, el hilo receptor se trabaría en la escritura, bloqueándose mutuamente. Cuando el hilo receptor está por emitir, un objeto <classname>sigc::signal&lt;void&gt;</classname> normal puede usarse en su lugar.Un <classname>Grid</classname> establece dinámicamente widgets hijos en filas y columnas. No es necesario especificar las dimensiones de la red en el constructor.Un <classname>Notebook</classname> tiene un conjunto de <literal>páginas</literal> apiladas, cada una de ellas contiene widgets. Las <literal>pestañas</literal> etiquetadas permiten al usuario seleccionar las páginas. Los <classname>Notebook</classname> permiten colocar varios conjuntos de widgets en un espacio reducido, mostrando sólo una página a la vez. Por ejemplo, se utilizan a menudo en los diálogos de preferencias.Un <classname>Plug</classname> es un tipo especial de ventana que se puede conectar a un <classname>Socket</classname>. Además de las propiedades y los métodos normales de <classname>Gtk::Window</classname>, un <classname>Plug</classname> proporciona un constructor que toma el ID de un <classname>Socket</classname>, lo que automáticamente incrusta el <classname>Plug</classname> en el <classname>Socket</classname> que coincide con el ID.Una <classname>ProgressBar</classname> es horizontal y de izquierda a derecha de manera predeterminada, pero se puede cambiar a una barra de progreso vertical mediante el uso del método <methodname>set_orientation()</methodname>.Un objeto <classname>RecentInfo</classname> es esencialmente un objeto que contiene todos los metadatos de un solo archivo utilizado recientemente. Puede utilizar este objeto para buscar cualquiera de las propiedades enumeradas <link linkend="list-file-metadata">anteriormente</link>.Un <classname>Socket</classname> es un tipo especial de widget contenedor que ofrece la posibilidad de incorporar widgets de un proceso en otro proceso de manera que sea transparente para el usuario.Una <classname>ToolPalette</classname> es similar a una <classname>Toolbar</classname>, pero puede contener una rejilla de elementos categorizados en grupos. El usuario puede ocultar o expandir cada grupo. Al igual que en una barra de herramientas, los elementos pueden aparecer sólo como iconos, como sólo texto, o en forma de iconos con el texto.Un objeto <classname>sigc::signal</classname> debe considerarse propiedad del hilo que lo creó. Solo ese hilo debe conectar un objeto <classname>sigc::slot</classname> al objeto de la señal, y solo ese hilo debe llamar a <methodname>emit()</methodname> u <methodname>operator()()</methodname> sobre la señal, o anular cualquier objeto <classname>sigc::slot</classname> conectado. Sigue (junto a otras cosas) que cualquier objeto de señal proporcionado por un widget de <application>gtkmm</application> solo se opere en el hilo principal de la IGU y cualquier objeto que derive de <classname>sigc::trackable</classname> con métodos no estáticos referenciados por «slots» conectados al objeto de señal solo deben destruirse en ese hilo.Un objeto <classname>sigc::slot</classname> creado por una llamada a <function>sigc::mem_fun()</function> que referencia un método de una clase que deriva de <classname>sigc::trackable</classname> nunca debe copiarse a otro hilo, ni otro hilo aparte del que lo creó lo debe destruir. (Una consecuencia de esto es que <methodname>Glib::Threads::Thread::create()</methodname> no debe llamarse con un argumento de «slot» creado por una llamada a <function>sigc::mem_fun()</function> que represente a un método de una clase semejante. Sin embargo, es seguro pasarle <methodname>Glib::Threads::Thread::create()</methodname> a un objeto de función representando un método así usando, por ejemplo, <function>boost::bind()</function> o, en C++11, <function>std::bin()</function> o una expresión lambda de C++11).Se puede agregar un widget hijo a <classname>EventBox</classname> utilizando:A continuación se muestra un pequeño ejemplo. Para usar el ejemplo, sólo ejecútelo desde un terminal; no crea una ventana. Creará una tubería llamada <literal>testfifo</literal> en la carpeta actual. Después inicie otro intérprete de comandos y ejecute <literal>echo "Hello" &gt; testfifo</literal>. El ejemplo imprimirá cada línea que introduzca hasta que ejecute <literal>echo "Q" &gt; testfifo</literal>.Una característica elegante de Glib (una de las bibliotecas subyacentes de <application>gtkmm</application>) es la capacidad de verificar los datos en un descriptor de archivos. Esto es especialmente útil para aplicaciones de red. Se usa el siguiente método para lograrlo:Una aplicación adecuadamente internacionalizada no asumirá nada sobre el número de bytes en un carácter. Eso significa que no debe usar aritmética de punteros para avanzar sobre los caracteres en una cadena, y significa que no debe usar <classname>std::string</classname> o funciones estándar de C como <function>strlen()</function> porque asumen lo mismo.Una regla para la cual puede haber excepciones: si la función virtual de C devuelve un puntero a un objeto derivado de <classname>GObject</classname>, es decir un objeto cuyas referencias se cuentan, entonces la función virtual de C++ deberá devolver un objeto <classname>Glib::RefPtr&lt;&gt;</classname>. Se requiere uno de los argumentos adicionales <parameter>refreturn</parameter> o <parameter>refreturn_ctype</parameter>.Un puntero inteligente actúa como un puntero normal. Aquí hay algunos ejemplos.Un objetivo puede estar en una variedad de formatos binarios. Este capítulo, y los ejemplos, asumen que los datos están en texto de 8 bits. Esto permite usar un formato XML para los datos del portapapeles. Sin embargo, probablemente no sea apropiado para datos binarios como imágenes. <classname>Gtk::Clipboard</classname> proporciona sobrecargas que le permiten especificar el formato en mayor detalle si es necesario.AM_CPPFLAGSAM_CPPFLAGS = ... -DPROGRAMNAME_LOCALEDIR=\"${PROGRAMNAME_LOCALEDIR}\"AM_CXXFLAGSATKAboutDialogAcceso a widgetsAccionesModo de actividadAñada <literal>INTLTOOL_FILES</literal> a la lista de archivos <literal>EXTRA_DIST</literal>. Esto asegura que cuando haga un <command>make dist</command>, este comando se incluya en el archivo fuente.Añada <literal>po</literal> a la variable <literal>SUBDIRS</literal>. Sin esto, las traducciones no se construirán al construir el programa.Añadir un constructor predeterminado.Añadir métodos para envolver las partes de la API de C.Añadir filas al modelo con los métodos <methodname>append()</methodname>, <methodname>prepend()</methodname>, o <methodname>insert()</methodname>.Agregar elementos a la lista de archivos recientesAñadir filasAñadir columnas a la vistaAñadiendo filas secundariasIncorporar propiedades, y asegurar que interactúan con otras propiedades correctamente, es relativamente difícil de corregir en la biblioteca de C, pero es posible, por lo que rellene un informe de error e intente enviar un parche al mantenedor correspondiente.Añadir widgetsOpciones de línea de comandos adicionales pasadas al «script» <filename>generate_wrap_init.pl</filename>, como el espacio de nombres de C++ y el prefijo de la carpeta padre de los archivos de cabecera.Además, el botón 3 del ratón se puede usar para saltar directamente a los valores <literal>upper</literal> o <literal>lower</literal>.Interioridades del ajusteAjustesLuego de que se crea un objeto <classname>Socket</classname> o <classname>Plug</classname>, puede obtener su ID con su función <methodname>get_id()</methodname>. Este ID puede entonces compartirse con otros procesos para que estos sepan cómo conectarse entre sí.Después de añadirle las filas a este modelo, deberá proporcionárselo al <classname>ComboBox</classname> con el método <methodname>set_model()</methodname>. Luego, use los métodos <methodname>pack_start()</methodname> o <methodname>pack_end()</methodname> para especificar qué columnas se mostrarán en el «ComboBox». Al igual que con el «TreeView», podrá usar el «CellRenderer» predeterminado pasándole la <classname>TreeModelColumn</classname> a los métodos de empaquetado, o puede instanciar un <classname>CellRenderer</classname> específico y definir un mapeado particular con <methodname>add_attribute()</methodname> o <methodname>set_cell_data_func()</methodname>. Tenga en cuenta que estos métodos están en la clase base <classname>CellLayout</classname>.Después de haber construido y ejecutado este programa, pruebe a redimensionar la ventana para observar su comportamiento. Además, pruebe modificar las opciones a <methodname>pack_start()</methodname> mientras lee la sección <link linkend="sec-boxes">Cajas</link>.Después de haber dibujado el contorno, se recorre el reloj dibujando marcas por cada hora, con una marca más grande en la posición de las 12, 3, 6, y 9. Ahora, está finalmente listo para implementar la función del reloj, mostrar la hora, lo que simplemente implica obtener los valores actuales de la hora, minutos, y segundos, y dibujar las manecillas en los ángulos correctos.Después de poner el código fuente en <literal>simple.cc</literal> puede compilar el programa anterior con gcc usando: <placeholder-1/> Tenga en cuenta que debe poner la invocación <literal>pkg-config</literal> entre apóstrofes. Los apóstrofes permiten a la shell ejecutar el comando dentro de ellos, y utilizar la salida de comando como parte de la línea de comandos. También tenga en cuenta que <literal>simple.cc</literal> debe venir antes de la invocación de <literal>pkg-config</literal> en la línea de comandos.Después de haber seleccionado el elemento del menú <guimenuitem>Recent Files Dialog</guimenuitem>, debería ver algo similar a la siguiente ventana.Después de haber configurado el conjunto de módulos correcto, necesitará decirle a <application>jhbuild</application> qué módulo o módulos construir. Para construir a <application>gtkmm</application> y a todas sus dependencias, asigne <varname>modules</varname> así: <placeholder-1/>Después de haber ejecutado <filename>socket</filename>, debería ver la siguiente salida en la terminal:Después de esto debería ver algo así:Después de que haya creado y configurado el filtro para seleccionar sólo los elementos que quiera, podrá aplicárselo a un widget selector con la función <methodname>RecentChooser::add_filter()</methodname>.Después de terminar de crear su camino, todavía no ha dibujado nada visible. Para hacer el camino visible, debe usar la función <methodname>stroke()</methodname> que rellenará el camino actual con la anchura y estilo de línea que se ha especificado en su objeto <classname>Cairo::Context</classname>. Después de rellenar, el camino actual se despejará para que pueda comenzar el próximo.Después de haber instalado todas las dependencias, descargue el código fuente de <application>gtkmm</application>, descomprímalo y cámbiese a la carpeta creada. <application>gtkmm</application> se puede construir e instalar con la siguiente secuencia de comandos:Después de que haya instalado la versión de git de <application>gtkmm</application>, ya estará listo para comenzar a usarlo y a experimentar con él. Para usar la versión nueva de <application>gtkmm</application> que ha acabado de instalar, necesitará establecer algunas variables de entorno para que su script <filename>configure</filename> sepa dónde encontrar las bibliotecas nuevas. Afortunadamente, <application>jhbuild</application> ofrece una solución fácil a este problema. Ejecutar el comando <command>jhbuild shell</command> arrancará un intérprete nuevo con todas las variables de entorno correctas establecidas. Ahora, si reconfigura y construye su proyecto como hace siempre, debería enlazarse con las bibliotecas recientemente instaladas. Para volver a su entorno previo, simplemente salga del intérprete de <application>jhbuild</application>.AhlstedtAlignmentTodos los programas <application>gtkmm</application> deben incluir ciertas cabeceras <application>gtkmm</application>: <literal>gtkmm.h</literal> incluye el kit completo de <application>gtkmm</application>. Esto no suele ser una buena idea, ya que incluye casi un megabyte de cabeceras, pero para programas sencillos, basta.Todos los widgets contenedores derivan de <classname>Gtk::Container</classname>, no siempre directamente. Algunos widgets contenedores, como <classname>Gtk::Grid</classname> pueden contener varios widgets hijos, por lo que típicamente tienen interfaces más complejas. Otros, como <classname>Gtk::Frame</classname> contienen sólo un widget hijo.Toda la API obsoleta se quitó en <application>gtkmm</application> 3.0, sin embargo, se marcarán más partes como obsoletas en versiones futuras.Todas las menciones de <varname>skeleton</varname> deben reemplazarse por el nombre correcto de la biblioteca de C que está envolviendo, como «something» o «libsomething». De la misma manera, todas las instancias de <varname>SKELETON</varname> deben reemplazarse por «SOMETHING» o «LIBSOMETHING», y todas las apariciones de <varname>Skeleton</varname> deben cambiarse por «Something».Además, pueden dibujar el valor en diferentes posiciones relativas al canal, especificadas por el método <methodname>set_value_pos()</methodname>.Alternativamente, si una lista completa de entradas posibles fuera muy larga o demasiado incómoda para generar, puede especificar en su lugar un espacio para una retrollamada con <methodname>set_match_func()</methodname>. Esto también es útil si no desea usar el principio de la cadena.Alternativamente, puede permitirle al contenedor de un widget controlar cuándo se destruye. En la mayoría de los casos, querrá que un widget dure sólo tanto tiempo como el contenedor en el que está. Para delegarle la gestión de la vida del widget a su contenedor, primero créelo con <function>Gtk::manage()</function> y empaquételo en su contenedor con <methodname>Gtk::Container::add()</methodname>, <methodname>Gtk::Box::pack_start()</methodname>, o un método similar. Ahora el widget se destruirá cuando se destruya su contenedor.A pesar de que <application>glib</application> en sí es segura para hilos, cualquier envoltorio de <application>glibmm</application> que use <application>libsigc++</application> no lo será. Entonces por ejemplo solo el hilo en el bucle principal debe llamar a <methodname>Glib::SignalIdle::connect()</methodname>, <methodname>Glib::SignalIO::connect()</methodname>, <methodname>Glib::SignalTimeout::connect()</methodname>, <methodname>Glib::SignalTimeout::connect_seconds</methodname> para ese bucle principal, o manipular cualquier objeto <classname>sigc::connection</classname> que devuelvan.A pesar de que las instancias de widgets <application>gtkmm</application> tienen ámbito y duración de la misma manera que otras clases de C++, <application>gtkmm</application> tiene una característica opcional para ahorrar tiempo que verá en algunos de los ejemplos. <function>Gtk::manage()</function> le permite decir que un widget hijo es propiedad del contenedor en el que lo ubica. Esto le permite utilizar <function>new</function> en el widget, añadirlo al contenedor, y olvidarse de eliminarlo. Puede aprender más de las técnicas de gestión de memoria de <application>gtkmm</application> en el <link linkend="chapter-memory">capítulo de gestión de memoria</link>.A pesar de que Cairo puede generar texto, no está pensado para reemplazar a Pango. Pango es una mejor elección si necesita generar texto más avanzado, por ejemplo, con ajuste de línea o elipses. Sólo debe dibujar texto con Cairo si éste es parte de un gráfico.A pesar de que la señal <literal>custom_widget_apply</literal> proporciona al widget que creó previamente, para simplificar las cosas puede mantener a los widgets que espera que contengan entrada del usuario como miembros de clase. Por ejemplo, si tiene un <classname>Gtk::Entry</classname> llamado <literal>m_Entry</literal> como miembro de su clase <classname>CustomPrintOperation</classname>: <placeholder-1/>A pesar de que el nombre <classname>EventBox</classname> hace énfasis en el método de manipulación de eventos, el widget también puede usarse para recortar (y para más cosas; consulte el ejemplo más abajo).Aunque se puede especificar el diseño y apariencia de las ventanas y widgets con código C++, es probable que resulte más conveniente usar <literal>Glade</literal> para el diseño de la interfaz de usuario y cargarlos en tiempo de ejecución con <literal>Gtk::Builder</literal>. Consulte el capítulo <link linkend="chapter-builder">Glade y Gtk::Builder</link>.A pesar de que, teóricamente, puede implementar su propio modelo, normalmente usará las clases de los modelos <classname>ListStore</classname> o <classname>TreeStore</classname>.A pesar de que puede usar código C++ para instanciar y ordenar widgets, esto puede pronto volverse tedioso y repetitivo; y requiere una recompilación para mostrar los cambios. La aplicación <application>Glade</application> le permite distribuir widgets en la pantalla y luego guardar una descripción XML de la distribución. Su aplicación podrá entonces usar la API <application>Gtk::Builder</application> para cargar ese archivo XML en tiempo de ejecución y obtener un puntero a instancias de widgets nombradas específicamente.A pesar de que su contenedor puede tener su propio método para establecer widgets hijos, aún así debe proporcionar una implementación para los métodos virtuales <methodname>on_add()</methodname> y <methodname>on_remove()</methodname> de la clase base, para que los métodos add() y remove() hagan algo apropiado si se llaman.A pesar de que, en la mayoría de los casos, el programador preferirá permitirle a los contenedores destruir a sus hijos automáticamente usando <function>Gtk::manage</function> (vea abajo), no se requiere que el programador use <function>Gtk::manage()</function>. Los operadores <literal>new</literal> y <literal>delete</literal> tradicionales también pueden usarse. <placeholder-1/> Aquí, el programador elimina <varname>pButton</varname> para evitar una fuga de memoria.Un <classname>Assistant</classname> divide una operación compleja en pasos. Cada paso es una página, conteniendo una cabecera, un widget hijo, y un área de acción. El área de acción del asistente tiene botones de navegación que se actualizan automáticamente dependiendo del tipo de la página, establecido con <methodname>set_page_type()</methodname>.Un widget <classname>Entry</classname> puede mostrar una barra de progreso dentro del área del texto, bajo el texto introducido. La barra de progreso se mostrará si se llama a los métodos <methodname>set_progress_fraction()</methodname> o <methodname>set_progress_pulse_step()</methodname>.Una <classname>InfoBar</classname> puede mostrar pequeños elementos de información o hacer preguntas breves. A diferencia de un <classname>Dialog</classname>, aparece encima de la ventana actual en vez de en una ventana nueva. Su API es muy similar a la del <link linkend="chapter-dialogs">Gtk::Dialog</link>.Un «Hola mundo» mejoradoAnastasovY aquí hay un extracto de una sesión de <application>gdb</application>. <placeholder-1/> La excepción se atrapa en <application>glibmm</application>, y el programa termina con una llamada a <function>g_error()</function>. Otras excepciones pueden resultar en un comportamiento diferente, pero en cualquier caso la excepción desde el manejador de señales se atrapa en <application>glibmm</application> o <application>gtkmm</application>, y <application>gdb</application> no puede ver dónde se lanzó.Otra cosa notable acerca de este ejemplo es que se ha hecho la llamada a <methodname>connect()</methodname> dos veces para el mismo objeto de señal. Esto está perfectamente bien: cuando se pulse el botón, se llamará a ambos manejadores de señales.Otra manera de destruir la conexión es su manejador de señales. Tiene que ser del tipo <classname>sigc::slot&lt;bool&gt;</classname>. Como puede observar en la definición, su manejador de señales tiene que devolver un valor del tipo <literal>bool</literal>. Una definición de un método de ejemplo podría verse así: <placeholder-1/>Otra solución es añadir una función <function>*_construct()</function> que el constructor de C++ pueda llamar después de haber instanciado su propio tipo. Por ejemplo, <placeholder-1/>Cualquier objeto <classname>sigc::connection</classname> solo debe considerarse propiedad del hilo en el que se llamó al método que devuelve el objeto <classname>sigc::connection</classname>. Solo ese hilo debe llamar a métodos de <classname>sigc::connection</classname> sobre el objeto.Cualquier archivo de fuentes <filename>.h</filename> y <filename>.cc</filename> adicional no generado se puede poner en <filename>skeleton/skeletonmm/</filename> y listar en <filename>skeleton/skeletonmm/filelist.am</filename>, típicamente en las variables <varname>files_extra_h</varname> y <varname>files_extra_cc</varname>.Tiempo de vida de la aplicaciónAplicar etiquetasAl igual que antes, casi todo lo interesante se hace en el manejador de señal de dibujo <methodname>on_draw()</methodname>. Antes de profundizar en el manejador de señal de dibujo, tenga en cuenta que el constructor del widget <classname>Clock</classname> conecta una función manejadora <methodname>on_timeout()</methodname> a un temporizador con un período de espera de 1000 milisegundos (1 segundo). Esto significa que <methodname>on_timeout()</methodname> se llamará una vez por segundo. La única responsabilidad de esta función es invalidar la ventana para que <application>gtkmm</application> se vea forzado a redibujarla.Como se mencionó anteriormente, cada <classname>TextView</classname> tiene un <classname>TextBuffer</classname>, y uno o más <classname>TextView</classname> pueden compartir el mismo <classname>TextBuffer</classname>.Como se mencionó anteriormente, <classname>Gtk::Adjustment</classname> puede emitir señales. Así es, por supuesto, cómo suceden las actualizaciones automáticamente cuando comparte un objeto <classname>Adjustment</classname> entre una <classname>Scrollbar</classname> y otro widget ajustable; todos los widgets ajustables conectan manejadores de señales a la señal <literal>value_changed</literal> de sus ajustes, como también puede su programa.Además de renombrar las carpetas, se deben renombrar algunos de los archivos de fuentes. Por ejemplo: <placeholder-1/> Algunos de los archivos esqueleto todavía deberán llenarse después con contenido específico del proyecto.Como se explicará en la sección <link linkend="chapter-adjustment">ajuste</link>, todos los widgets del rango están asociados a un objeto <classname>Adjustment</classname>. Para cambiar los valores inferior, superior y actual del widget debe usar los métodos de su <classname>Adjustment</classname>, que puede obtenerlos con el método <methodname>get_adjustment()</methodname>. Los constructores predeterminados de los widgets <classname>Range</classname> crean un <classname>Adjustment</classname> automáticamente, o puede especificar un <classname>Adjustment</classname> existente, tal vez para compartirlo con otro widget. Consulte la sección <link linkend="chapter-adjustment">ajuste</link> para obtener más detalles.Al igual que con las <classname>Scrollbar</classname>s, la orientación puede ser horizontal o vertical. El constructor predeterminado crea un <classname>Adjustment</classname> con todos sus valores establecidos a <literal>0.0</literal>. Esto no es útil, por lo que necesitará establecer algunos detalles del <classname>Adjustment</classname> para obtener un comportamiento significativo.Dejando de lado el hecho de que los «slot» conectados siempre se ejecutan en el hilo receptor, los objetos <classname>Glib::Dispatcher</classname> son similares a los objetos <classname>sigc::signal&lt;void;&gt;</classname>. Por lo tanto, no pueden pasar argumentos sin vincular ni devolver un valor. La mejor manera de pasar esos argumentos es con una cola segura para hilos (asíncrona). Al momento de escritura, <application>glibmm</application> no tiene una, pero mucha gente escribiendo código de hilos múltiples tendrá una disponible (son relativamente fáciles de escribir a pesar de que son detalles de combinar seguridad de hilos con seguridad fuerte de excepciones).AspectFrameAsistenteAsumir el tamaño de las cadenas mostradasOperaciones asíncronasEn tiempo de instalación, los archivos <filename>.po</filename> se convierten a formato binario (con la extensión <filename>.mo</filename>) y se ponen en una carpeta de sistema para archivos de localización, por ejemplo <filename>/usr/share/locale/</filename>.Como mínimo, la función <function>_new()</function> no debe usar ninguna API privada (funciones que sólo están en un archivo .c). Incluso cuando no hay funciones, a veces se pueden reimplementar 2 ó 3 líneas de código en una función <function>_new()</function> siempre que esas líneas de código usen una API que esté disponible.Por el momento, existen herramientas separadas para generar partes diferentes de estos <filename>.defs</filename>, por lo que se parten en archivos separados. Por ejemplo, en la carpeta <filename>gtk/src</filename> de las fuentes de <application>gtkmm</application>, encontrará estos archivos: <placeholder-1/>Celdas editables guardadas automáticamente.Tipos básicos equivalentesTipos básicosConceptos básicosDado que el usuario puede introducir texto arbitrario, una fila del modelo activa es suficiente para indicar qué texto ha introducido el usuario. Por lo tanto, debe obtener el widget <classname>Entry</classname> con el método <methodname>ComboBoxEntry::get_entry()</methodname> y llamar a <methodname>get_text()</methodname> sobre él.Dado que esta transformación automática no es siempre apropiada, tal vez quiera proporcionar texto escrito a mano para un método particular. Puede hacer esto copiando el nodo XML para la función de su archivo <filename>something_docs.xml</filename> al archivo <filename>something_docs_override.xml</filename> y cambiando el contenido.Antes de intentar instalar <application>gtkmm</application> 3.0, probablemente deba instalar primero estos otros paquetes.Abajo se muestra un ejemplo corto que ilustra estas funciones. Este ejemplo hace uso del widget «Marco» para demostrar mejor los estilos de etiquetas. (El widget «Marco» se explica en la sección <link linkend="sec-frame">Marco</link>). Esto es posible gracias que el primer carácter de <literal>m_Label_Normal</literal> aparece subrayado cuando pulsa la tecla <keycap>Alt</keycap>.BernhardAdemás de indicar la cantidad de progreso que se ha completado, la barra de progreso también puede usarse para indicar que ocurre actividad; esto se realiza poniendo la barra en <emphasis>modo de actividad</emphasis>. En este modo, la barra de progreso muestra un pequeño rectángulo que se mueve hacia adelante y atrás. El modo de actividad es útil en las situaciones en las que el progreso de una operación no se puede calcular como un rango de valores (por ejemplo, cuando se recibe un archivo de tamaño desconocido).Enlazar argumentos adicionalesBjarne Stroustrup, «The C++ Programming Language»: sección 34.3Caja de empaquetado 1Caja de empaquetado 2CajasConstruir aplicaciones <application>gtkmm</application> en Win32Pero a diferencia de la mayoría de punteros inteligentes, no se puede utilizar el operador * para acceder a la instancia de base.Pero, a diferencia de los punteros normales, los <classname>RefPtr</classname> se inicializan automáticamente a nulo, por lo que no necesita recordar hacerlo.BotónLas cajas de botones son una manera conveniente de ordenar rápidamente un grupo de botones. Su orientación puede ser tanto horizontal como vertical.Las cajas de botones soportan varios estilos de disposición. Puede obtener y modificar el estilo usando <methodname>get_layout()</methodname> y <methodname>set_layout()</methodname>. ButtonBoxCajas de BotonesBotonesLos botones se añaden a una <classname>ButtonBox</classname> con el método <methodname>add()</methodname>.Por convenio, los objetos de glib/GTK+ tienen funciones <function>*_new()</function>, como <function>example_widget_new()</function> que no hacen más que llamar a <function>g_object_new()</function> y devolver el resultado. Los parámetros de entrada se proporcionan a <function>g_object_new()</function> junto con los nombres de las propiedades a las que se asignan. Por ejemplo, <placeholder-1/>Por convenio, las estructuras se declaran en los encabezados de Glib/GTK+ igual que en: <placeholder-1/>De manera predeterminada, <application>gtkmm</application> se instalará en la carpeta <filename>/usr/local</filename>, En algunos sistemas es posible que necesite instalar en una ubicación diferente. Por ejemplo, en sitemas Red Hat Linux puede utilizar la opción <literal>--prefix </literal>, de este modo: <screen># ./configure --prefix=/usr</screen>De manera predeterminada, <application>jhbuild</application> está configurado para instalar todo el software construido con <application>jhbuild</application> bajo el prefijo <filename>/opt/gnome</filename>. Puede elegir un prefijo diferente, pero se recomienda que lo mantenga diferente de otro software que haya instalado (no lo establezca a <filename>/usr</filename>). Si ha seguido las instrucciones de jhbuild, entonces este prefijo le corresponde a su usuario, por lo que no necesitará ejecutar jhbuild como <literal>root</literal>.De manera predeterminada, <methodname>PrintOperation::run()</methodname> retorna cuando una operación de impresión ha terminado. Si necesite ejecutar una operación no modal de impresión, llame a <methodname>PrintOperation::set_allow_async()</methodname>. Tenga en cuenta que, a pesar de que no todas las plataformas soportan <methodname>set_allow_async()</methodname>, la señal <literal>done</literal> se emitirá de todos modos.De manera predeterminada, sólo se pueden seleccionar filas únicas, pero puede permitir la selección múltiple estableciendo el modo, así: <placeholder-1/>De manera predeterminada, sus manejadores de señales se llaman después de cualquier manejador de señales conectado previamente. Sin embargo, esto puede ser un problema con las señales de eventos de X. Por ejemplo, los manejadores de señales existentes, o el manejador de señales predeterminado, podrían devolver <literal>true</literal> para que no se llamen a otros manejadores. Para especificar que el suyo debe llamarse antes que los otros, y que de esta manera siempre se llame, puede asignar <literal>false</literal> al parámetro opcional <literal>after</literal>. Por ejemplo, <placeholder-1/>Derivando directamente de <classname>Gtk::Widget</classname> puede hacer todo el dibujo de su widget directamente, en lugar de sólo ordenar widgets hijos. Por ejemplo, una <classname>Gtk::Label</classname> dibuja el texto de la etiqueta, pero no hace esto usando a otros widgets.Reemplazar <methodname>forall_vfunc()</methodname> puede permitirle a las aplicaciones operar en todos los widgets hijos de los contenedores. Por ejemplo, <methodname>show_all_children()</methodname> usa esto para encontrar a todos los widgets hijos y mostrarlos.Los programadores de C usan <function>sprintf()</function> para componer y concatenar cadenas. C++ favorece los flujos, pero desafortunadamente, este enfoque hace la traducción difícil, porque cada fragmento de texto se traduce separadamente, sin permitirle a los traductores reordenarlos de acuerdo a la gramática del lenguaje.Tipo de CTipo de C++Cairo y PangoLlame a <methodname>show()</methodname> para mostrar al widget.Conversión de tiposEl usuario puede editar las celdas en una <classname>TreeView</classname> directamente. Para permitir esto, use los métodos <classname>Gtk::TreeView</classname> <methodname>insert_column_editable()</methodname> y <methodname>append_column_editable()</methodname> en lugar de <methodname>insert_column()</methodname> y <methodname>append_column()</methodname>. Cuando estas celdas se editen, los nuevos valores se guardarán inmediatamente en el modelo. Tenga en cuenta que estos métodos son plantillas que sólo se pueden instanciar para tipos de columnas simples como <classname>Glib::ustring</classname>, int, y long.Cambios en <application>gtkmm</application> 3Cambiar la disposición de una ventana «al vuelo» para, por ejemplo, hacer que algunos widgets adicionales aparezcan, es complejo. Requiere un cálculo tedioso de la posición de cada widget.Cambiar la selecciónCapítulo acerca de «Dibujar con Cairo».Capítulo acerca de «Programas con múltiples hilos».Capítulo acerca de «Imprimir».Capítulo acerca de «Archivos recientes».Capítulo acerca de «Tiempos de espera».Capítulo acerca de «Trabajar con el código fuente de gtkmm».Capítulo acerca de «Eventos del teclado».Casilla de verificaciónCasillas de verificaciónVerificar si es nuloLos widgets hijos pueden abarcar múltiples filas o columnas, usando <methodname>attach()</methodname>, o añadirse a un widget existente dentro de la cuadrícula con <methodname>attach_next_to()</methodname>. Se puede establecer que las filas o columnas individuales de la cuadrícula tengan una altura o ancho uniforme con <methodname>set_row_homogeneous()</methodname> y <methodname>set_column_homogeneous()</methodname>.ChrisWidgets de alcance de claseMacros de clasesPortapapeles: idealPortapapeles: simpleColorChooserDialogCajas combinadasComboBox«ComboBox» con una entrada«ComboBox» con una entradaComboBoxText«ComboBoxText» con una entradaComparación con otros sistemas de señalesComposición de cadenasConecte las señales que quiere usar a los manejadores apropiados.Conectar «plugs» y «sockets»Conectar manejadores de señalesObjetos constantes usados a través de <classname>RefPtr</classname>: si la función no debe cambiar el objeto, asegúrese de que el objeto es constante, incluso si el <classname>RefPtr</classname> ya lo es. Por ejemplo, <code>const Glib::RefPtr&lt;const Gtk::FileFilter&gt;&amp; filter</code>.ConstanciaMacros de constructoresConstructoresWidgets contenedoresAl contrario que otros eventos, los eventos del teclado primero se envían a la ventana de nivel superior (<classname>Gtk::Window</classname>), donde se verifican los atajos del teclado establecidos (teclas aceleradoras y combinaciones, utilizadas para seleccionar elementos del menú desde el teclado). Después de esto (y asumuiendo que no se manejó el evento), se envía al widget que tiene el foco, y la propagación comienza desde allí.ContribuirCopiarCopiadoCopiar el esqueleto del proyectoCree un <classname>Plug</classname> independiente de cualquier <classname>Socket</classname> particular y pásele el ID del <classname>Plug</classname> a otros procesos que necesiten usarlo. El ID del <classname>Plug</classname> puede asociarse con un objeto <classname>Socket</classname> particular usando la función <methodname>Socket::add_id()</methodname>. Este es el enfoque utilizado en el siguiente ejemplo.Cree un objeto <classname>Socket</classname> en un proceso y pásele el ID de ese <classname>Socket</classname> a otro proceso para que pueda crear un objeto <classname>Plug</classname> mediante la especificación del ID del <classname>Socket</classname> dado en su constructor. No hay manera de asignar un <classname>Plug</classname> a un <classname>Socket</classname> particular después de su creación, por lo que le debe pasar el ID del <classname>Socket</classname> al constructor del <classname>Plug</classname>.Cree una subcarpeta llamada <literal>po</literal> en la carpeta raíz de su proyecto. Esta carpeta eventualmente contendrá todas sus traducciones. Dentro de ella, cree un archivo llamado <literal>LINGUAS</literal> y otro llamado <literal>POTFILES.in</literal>. Es práctica común crear también un archivo <literal>ChangeLog</literal> en la carpeta <literal>po</literal> para que los traductores puedan rastrear los cambios de las traducciones.Cree sus propias señales en lugar de pasar punteros. Los objetos se pueden comunicar entre sí a través de las señales y manejadores de señales. Esto es mucho más simple que objetos que contengan punteros y llamen a sus métodos entre sí. Las clases de <application>gtkmm</application> usan versiones especiales de <classname>sigc::signal</classname>, pero debe usar <classname>sigc::signal</classname> normales, como se describe en la documentación de <application>libsigc++</application>.Crear archivos .hg y .ccgCrear un ajusteCrear sus propias señalesCummingActualmente, <application>gettext</application> no soporta caracteres no ASCII (es decir, cualquier carácter con un código superior a 127) en el código fuente. Por ejemplo, no puede usar el signo de derechos de autor (©).Contenedor personalizadoContenedores personalizadosWidget personalizadoWidgets personalizadosDISTCLEANFILES = ... intltool-extract \
                 intltool-merge \
                 intltool-update \
                 po/.intltool-merge-cacheDanielDavidDeclare una variable del tipo del <classname>Widget</classname> que quiere usar, generalmente como variable miembro de una clase contenedora derivada. También puede declarar un puntero al tipo de widget, y luego crearlo con <literal>new</literal> en su código. Aún cuando use el widget a través de un puntero, probablemente lo mejor sea hacer que el puntero sea una variable miembro de una clase contenedora para que pueda acceder a él más tarde.Formato predeterminadoDefina <literal>INTLTOOL_FILES</literal> como: <placeholder-1/>Define un objetivo personalizado de portapapeles, a pesar de que el formato del objetivo es sólo texto.DependeciasEliminar referenciaLos diseñadores sin conocimientos de programación pueden crear y editar IU.DiálogosLos diálogos se usan como ventanas secundarias, para proporcionar información específica o hacer preguntas. Las ventanas <classname>Gtk::Dialog</classname> contienen algunos widgets pre-empaquetados para asegurar la consistencia, y un método <methodname>run()</methodname> que se bloquea hasta que el usuario cierra el diálogo.Diferentes aplicaciones contienen diferentes tipos de datos, y podrían hacer esos datos disponibles en una variedad de formatos. <application>gtkmm</application> llama a estos tipos de datos <literal>objetivos</literal>.Distintos tipos de uniones en CairoDesconectar manejadores de señalesDescubrir los objetivos disponiblesHace una <function>reference()</function> adicional en el valor de retorno de una función <function>something_vfunc()</function> reemplazada en la función de devolución de llamada de C, en caso de que la función de C que llama espere que proporcione una referencia.Hace una <function>reference()</function> adicional en el valor de retorno del método virtual <function>on_something()</function>, en caso de que la función de C no proporcione una referencia.Hace una <function>reference()</function> adicional en el valor de retorno de la función <function>something_vfunc()</function>, en caso de que la función virtual de C no proporcione una referencia.Hace una <function>reference()</function> adicional en el valor de retorno, en el caso de que la función de C no proporcione una referencia.No genera una devolución de llamada de C para la señal. Use esto cuando debe generar la función de devolución de llamada a mano.No genera una función de devolución de llamada de C para la «vfunc». Use esto cuando deba generar la función de devolución de llamada a mano.No genera una definición de la «vfunc» en el archivo <filename>.cc</filename>. Use esto cuando deba generar la «vfunc» a mano.No genera un método virtual <function>on_something()</function> para permitir reemplazar fácilmente el manejador de señales predeterminado. Use esto si añadir una señal con un manejador de señales predeterminado rompe la ABI incrementando el tamaño de la tabla de funciones virtuales de la clase.DocumentaciónEstructura de construcción de la documentaciónArrastrar y soltarDragContextDibujar arcos y círculosÁrea de dibujo: arcosÁrea de dibujo: imagenÁrea de dibujo: líneasÁrea de dibujo: textoÁrea de dibujo: líneas estrechasDibujar líneas curvasDibujar imágenesDibujar Lineas RectasDibujar textoDibujar texto con PangoDibujar en sentido anti-horarioDibujar líneas estrechasDibujar con coordenadas relativasMientras se realice un <literal>movimiento</literal>, el widget origen también emitirá esta señal: <placeholder-1/>Asignación dinamica mediante el uso de manage() y add()Asignación dinámica con new y deleteCada <classname>Cairo::Context</classname> se asocia a una <classname>Gdk::Window</classname> particular, por lo que la primera línea del ejemplo de abajo crea un widget <classname>Gtk::DrawingArea</classname> y la segunda línea usa su <classname>Gdk::Window</classname> asociada para crear un objeto <classname>Cairo::Context</classname>. Las dos últimas líneas cambian el estado gráfico del contexto.Cada <classname>Gtk::TextBuffer</classname> usa una <classname>Gtk::TextBuffer::TagTable</classname>, que contiene las <classname>Tag</classname> para ese búfer. Dos o más <classname>TextBuffer</classname> pueden compartir la misma <classname>TagTable</classname>. Cuando cree las <classname>Tag</classname>, añádalas a la <classname>TagTable</classname>. Por ejemplo:Cada <classname>Gtk::TreeView</classname> tiene un <classname>Gtk::Model</classname> asociado que contiene los datos mostrados por el <classname>TreeView</classname> Varios <classname>Gtk::TreeView</classname> puede usar el mismo <classname>Gtk::TreeModel</classname>. Por ejemplo, esto le permite mostrar y editar los mismos datos de 2 formas diferentes al mismo tiempo. O las 2 vistas pueden mostrar diferentes columnas de los mismos modelos de datos, de la misma manera que dos consultas SQL (o «vistas») pueden mostrar diferentes campos de la misma tabla de la base de datos.Cada elemento de la lista de archivos usados recientemente se identifica mediante su URI, y puede tener metadatos asociados. Los metadatos pueden usarse para especificar cómo se mostrará el archivo, su descripción, su tipo MIME, qué aplicación lo registró, si es privado de esta aplicación y muchas otras cosas.Cada línea contiene una <classname>Box</classname> horizontal con varios botones. Cada uno de los botones en una línea está empaquetado en la <classname>Box</classname>, con los mismos argumentos pasados al método <methodname>pack_start()</methodname>.Celdas editablesElstnerEmitida cuando el botón se pulsa y se suelta.Emitida cuando se pulsa el botón.Emitida cuando se suelta el botón.Emitida cuando el puntero del ratón sale del botón de la ventana.Emitida cuando se mueve el puntero del ratón sobre el botón de la ventana.EntryCompletado de «Entry»Ejemplo de completado de «Entry»Ejemplo de icono de «Entry»Iconos de «Entry»«Entry» de progresoEjemplo de «Entry» de progresoLos widgets de «entry» le permiten al usuario introducir texto. Puede cambiar el contenido con el método <methodname>set_text()</methodname>, y leer el contenido actual con el método <methodname>get_text()</methodname>.«Entry» con icono«Entry» con barra de progresoEnumeraciones.Propagación de eventosPropagación de eventos significa que, cuando se emite un evento en un widget particular, puede pasarse a su widget padre (y ese widget puede pasárselo a su padre, y así sucesivamente) y, si el padre tiene un manejador de eventos, se llamará.EventBoxEjemploAplicación de ejemplo: crear un reloj con CairoEjemplosExcepciones en manejadores de señalesEsperar UTF8Exportar a PDFExtender el diálogo de impresiónFerreiraSelector de archivosFileChooserDialogFiltrar los archivos recientesPor último, comprobar el estado. Por ejemplo, <placeholder-1/>Finalmente, para dejar que su programa use la traducción de la localización actual, añádale este código al principio de su archivo <filename>main.cc</filename>, para inicializar gettext. <placeholder-1/>Primero cree las <classname>Action</classname>s y añádaselas a un <classname>ActionGroup</classname>, con <methodname>ActionGroup::add()</methodname>.Primero, se instancia un objeto almacenado en un puntero inteligente <classname>RefPtr</classname> llamado <literal>app</literal>. Éste es del tipo <classname>Gtk::Application</classname>. Cada programa de <application>gtkmm</application> debe tener uno de estos. Le pasamos nuestros argumentos de línea de comandos a su método «create()». Toma los argumentos que quiere, y le deja el resto, como se ha descrito anteriormente.Primero, mire el ejemplo simple en el que se lanza una excepción desde una función normal (sin manejador de señales). <placeholder-1/>FontChooserDialogPara un CellRendererToggle, establecería la propiedad <emphasis>activable</emphasis> en su lugar.Para cualquiera de las clases <classname>RecentChooser</classname>, si no quiere mostrar todos los elementos en la lista de archivos recientes, puede filtrarlos para mostrar sólo aquellos que quiere. Puede realizar esto con ayuda de la clase <classname>RecentFilter</classname>. Esta clase le permite filtrar los archivos recientes por su nombre (<methodname>add_pattern()</methodname>), su tipo MIME (<methodname>add_mime_type()</methodname>), la aplicación que los registró (<methodname>add_application()</methodname>), o una función de filtrado personalizada (<methodname>add_custom()</methodname>). También proporciona la posibilidad de filtrar de acuerdo a cuánto tiempo pasó desde que el archivo se modificó y a qué grupo pertenece.Para cada página que necesita procesarse, se emiten las siguientes señales: <placeholder-1/>Por ejemplo, para <classname>Pango::Analysis</classname> en <filename>item.hg</filename>: <placeholder-1/>Por ejemplo, de <filename>icontheme.hg</filename>: <placeholder-1/>Por ejemplo, si hubiera una función de C que devolviera un <type>GtkWidget*</type> y por alguna razón, en lugar de hacer que el método de C++ también devuelva el widget, se quisiera hacer que el método de C++ ponga al widget en un parámetro de salida especificado, sería necesaria una macro de inicialización como la siguiente: <placeholder-1/>Por ejemplo, en <filename>rectangle.hg</filename>: <placeholder-1/>Por ejemplo, en Pangomm, <filename>layoutline.hg</filename>: <placeholder-1/>Para obtener información acerca de la implementación de sus propias señales en vez de sólo conectar a las señales existentes de <application>gtkmm</application>, consulte el <link linkend="chapter-custom-signals">apéndice</link>.Por ejemplo,Por ejemplo, <application>gedit</application> puede proporcionar y recibir el objetivo <literal>"UTF8_STRING"</literal>, para que pueda pegar datos en <application>gedit</application> desde cualquier aplicación que proporcione ese objetivo. O bien, dos aplicaciones de edición de imágenes diferentes podrían proporcionar y recibir una variedad de formatos de imágenes como objetivos. Mientras que una aplicación pueda recibir uno de los objetivos que la otra proporciona, entonces podrá copiar los datos de una a la otra.Por ejemplo, <placeholder-1/>Por ejemplo, para <classname>Gdk::Rectangle</classname>: <placeholder-1/>Por ejemplo, para <classname>Pango::AttrIter</classname>: <placeholder-1/>Por ejemplo, para <classname>Pango::Coverage</classname>: <placeholder-1/>Por ejemplo, para un CellRendererText, establecería la propiedad <emphasis>editable</emphasis> de la celda a «true», así:Por ejemplo, para <classname>Gdk::RGBA</classname>: <placeholder-1/>Por ejemplo, de <filename>accelgroup.hg</filename>: <placeholder-1/>Por ejemplo, de <filename>button.hg</filename>: <placeholder-1/>Por ejemplo, de <filename>buttonbox.hg</filename>: <placeholder-1/>Por ejemplo, de <filename>celleditable.hg</filename>: <placeholder-1/>Por ejemplo, de <filename>container.hg</filename>: <placeholder-1/>Por ejemplo, de <filename>entry.hg</filename>: <placeholder-1/>Por ejemplo, de <filename>enums.hg</filename>: <placeholder-1/>Por ejemplo, de <filename>pixbuf.hg</filename>: <placeholder-1/>Por ejemplo, de <filename>widget.hg</filename>: <placeholder-1/>Por ejemplo, este código podría ser problemático:Por ejemplo, para crear una señal que envíe 2 parámetros, un <type>bool</type> y un <type>int</type>, simplemente declare una <classname>sigc::signal</classname>, así: <placeholder-1/>Por ejemplo:Para obtener información más detallada acerca de señales, consulte el <link linkend="chapter-signals">apéndice</link>.Para la selección múltiple, debe definir un retorno llamada, y pasárselo a <methodname>selected_foreach()</methodname>, <methodname>selected_foreach_path()</methodname>, o <methodname>selected_foreach_iter()</methodname>, así:A manera de referencia, es posible generar un archivo que contenga todas las cadenas que aparecen en su código, incluso si no están marcadas para traducción, junto con las referencias al nombre de archivo y al número de línea. Para generar un archivo así llamado <literal>my-strings</literal>, ejecute el siguiente comando, dentro de la carpeta del código fuente: <placeholder-1/>Para la selección simple, puede simplemente llamar <methodname>get_selected()</methodname>, así:Para introducir contraseñas, frases de paso, y otra información que no quiera que aparezca en la pantalla, llamar a <methodname>set_visibility</methodname> con <literal>false</literal> hará que el texto permanezca oculto.MarcoLos cuadros pueden encerrar un grupo de widgets dentro de una caja, con un título opcional. Por ejemplo, tal vez quiera poner un grupo de <classname>RadioButton</classname> o <classname>CheckButton</classname> en un <classname>Frame</classname>.De vez en cuando, puede ser útil incrustar un widget de otra aplicación dentro de la suya. <application>gtkmm</application> le permite hacer esto con las clases <classname>Gtk::Socket</classname> y <classname>Gtk::Plug</classname>. Se anticipa que no muchas aplicaciones necesitan esta funcionalidad, pero en los raros casos en los que necesite mostrar un widget que esté ejecutándose en un proceso completamente diferente, estas clases pueden resultar muy útiles.Ejemplo completoWidgets de alcance de funciónGTK+ 3.0GTK+ y <application>gtkmm</application> están diseñados para funcionar correctamente con Microsoft Windows, y los desarrolladores fomentan su uso en la plataforma win32. Sin embargo, Windows no tiene un sistema de instalación estándar para las bibliotecas de desarrollo. Si quiere obtener instrucciones y notas para una instalación específica de Windows consulte la página <ulink url="http://live.gnome.org/gtkmm/MSWindows">Instalación en Windows</ulink>.GTK+ usa la API de dibujo <ulink url="http://cairographics.org">Cairo</ulink>. Con <application>gtkmm</application>, puede usar la API C++ <ulink url="http://www.cairographics.org/cairomm/">cairomm</ulink> para Cairo.Genera una declaración del método virtual <function>on_something</function> en el archivo <filename>.h</filename>, pero no genera una definición en el archivo <filename>.cc</filename>. Use esto cuando deba generar la definición a mano.Generar los archivos .defs.Generar los .defs de enumeracionesGenerar los .defs de métodosGenerar los .defs de señales y propiedadesLa generación del código fuente para una API envoltorio del estilo de gtkmm requiere el uso de herramientas como <command>gmmproc</command> y <filename>generate_wrap_init.pl</filename>. En teoría, podría escribir sus propios archivos de construcción para usarlas apropiadamente, pero una opción mucho mejor es hacer uso de la infraestructura de construcción proporcionada por el módulo mm-common. Para empezar, ayuda mucho escoger un módulo de enlace existente como un ejemplo para consultar.Obtenga los datos de los widgets en el manejador de señales <literal>custom_widget_apply</literal>.Obtener ayuda con las traduccionesObtener los valoresPásele todas las opciones de línea de comandos a <methodname>Gtk::Application::create()</methodname> y añada la opción <literal>Gio::APPLICATION_HANDLES_COMMAND_LINE</literal>. Conecte un manejador de señales a la señal <literal>command_line</literal>, y maneje las opciones de línea de comandos en él.Glade y Gtk::BuilderGlib::IO_ERR: llame a su método cuando haya ocurrido un error en el descriptor de archivos.Glib::IO_HUP: llame a su método cuando se cuelgue (la conexión se ha roto, normalmente por tuberías y «sockets»).Glib::IO_IN: llame a su método cuando haya datos listos para leerse en su descriptor de archivos.Glib::IO_OUT: llame a su método cuando el descriptor de archivos esté listo para la escritura.Glib::IO_PRI: llame a su método cuando el descriptor de archivos tenga datos urgentes para leer.Glib::RefPtr&lt;Gtk::Adjustment&gt; Gtk::Adjustment::create(
  double value,
  double lower,
  double upper,
  double step_increment = 1,
  double page_increment = 10,
  double page_size = 0);Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");Glib::RefPtr&lt;Gtk::Clipboard&gt; refClipboard = Gtk::Clipboard::get();

//Targets:
std::vector&lt;Gtk::TargetEntry&gt; targets;
targets.push_back( Gtk::TargetEntry("example_custom_target") );
targets.push_back( Gtk::TargetEntry("UTF8_STRING") );

refClipboard-&gt;set( targets,
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_get),
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_clear) );Glib::RefPtr&lt;Gtk::ListStore&gt; refListStore =
    Gtk::ListStore::create(m_Columns);Glib::RefPtr&lt;Gtk::RecentInfo&gt; info;
try
{
  info = recent_manager-&gt;lookup_item(uri);
}
catch(const Gtk::RecentManagerError&amp; ex)
{
  std::cerr &lt;&lt; "RecentManagerError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
}
if (info)
{
  // item was found
}Glib::RefPtr&lt;Gtk::RecentManager&gt; recent_manager = Gtk::RecentManager::get_default();
recent_manager-&gt;add_item(uri);Glib::RefPtr&lt;Gtk::TextBuffer::Mark&gt; refMark =
    refBuffer-&gt;create_mark(iter);Glib::RefPtr&lt;Gtk::TextBuffer::Tag&gt; refTagMatch =
    Gtk::TextBuffer::Tag::create();
refTagMatch-&gt;property_background() = "orange";Glib::RefPtr&lt;Gtk::TextBuffer::TagTable&gt; refTagTable =
    Gtk::TextBuffer::TagTable::create();
refTagTable-&gt;add(refTagMatch);
//Hopefully a future version of <application>gtkmm</application> will have a set_tag_table() method,
//for use after creation of the buffer.
Glib::RefPtr&lt;Gtk::TextBuffer&gt; refBuffer =
    Gtk::TextBuffer::create(refTagTable);Glib::RefPtr&lt;Gtk::TextChildAnchor&gt; refAnchor =
    refBuffer-&gt;create_child_anchor(iter);Glib::RefPtr&lt;Gtk::TreeModelSort&gt; sorted_model =
    Gtk::TreeModelSort::create(model);
sorted_model-&gt;set_sort_column(columns.m_col_name, Gtk::SORT_ASCENDING);
treeview.set_model(sorted_model);Glib::RefPtr&lt;Gtk::TreeSelection&gt; refTreeSelection =
    m_TreeView.get_selection();Glib::RefPtr&lt;Gtk::UIManager&gt; m_refUIManager =
    Gtk::UIManager::create();
m_refUIManager-&gt;insert_action_group(m_refActionGroup);
add_accel_group(m_refUIManager-&gt;get_accel_group());Glib::ustringGlib::ustring y std::iostreamsGlib::ustring strText = row[m_Columns.m_col_text];
int number = row[m_Columns.m_col_number];Glib::ustring ui_info =
    "&lt;ui&gt;"
    "  &lt;menubar name='MenuBar'&gt;"
    "    &lt;menu action='MenuFile'&gt;"
    "      &lt;menuitem action='New'/&gt;"
    "      &lt;menuitem action='Open'/&gt;"
    "      &lt;separator/&gt;"
    "      &lt;menuitem action='Quit'/&gt;"
    "    &lt;/menu&gt;"
    "    &lt;menu action='MenuEdit'&gt;"
    "      &lt;menuitem action='Cut'/&gt;"
    "      &lt;menuitem action='Copy'/&gt;"
    "      &lt;menuitem action='Paste'/&gt;"
    "    &lt;/menu&gt;"
    "  &lt;/menubar&gt;"
    "  &lt;toolbar  name='ToolBar'&gt;"
    "    &lt;toolitem action='Open'/&gt;"
    "    &lt;toolitem action='Quit'/&gt;"
    "  &lt;/toolbar&gt;"
    "&lt;/ui&gt;";

m_refUIManager-&gt;add_ui_from_string(ui_info);Glib::ustring ui_info =
    "&lt;ui&gt;"
    "  &lt;popup name='PopupMenu'&gt;"
    "    &lt;menuitem action='ContextEdit'/&gt;"
    "    &lt;menuitem action='ContextProcess'/&gt;"
    "    &lt;menuitem action='ContextRemove'/&gt;"
    "  &lt;/popup&gt;"
    "&lt;/ui&gt;";

m_refUIManager-&gt;add_ui_from_string(ui_info);GridGruposGtk::Alignment
Gtk::Arrow
Gtk::AspectFrame
Gtk::Bin
Gtk::Box
Gtk::Button
Gtk::CheckButton
Gtk::Fixed
Gtk::Frame
Gtk::Grid
Gtk::Image
Gtk::Label
Gtk::MenuItem
Gtk::Notebook
Gtk::Paned
Gtk::RadioButton
Gtk::Range
Gtk::ScrolledWindow
Gtk::Separator
Gtk::Table (marcado como obsoleto en la versión de <application>gtkmm</application> 3.4)
Gtk::ToolbarGtk::Application y opciones de línea de comandosGtk::Box(Gtk::Orientation orientation = Gtk::ORIENTATION_HORIZONTAL, int spacing = 0);
void set_spacing(int spacing);
void set_homogeneous(bool homogeneous = true);Gtk::Button* pButton = new Gtk::Button("_Something", true);Gtk::CellRendererToggle* pRenderer =
    Gtk::manage( new Gtk::CellRendererToggle() );
pRenderer-&gt;signal_toggled().connect(
    sigc::bind( sigc::mem_fun(*this,
        &amp;Example_TreeView_TreeStore::on_cell_toggled), m_columns.dave)
);Gtk::ComboBox ahora deriva de CellLayout, permitiendo una disposición y alineación más fácil de sus <classname>Gtk::CellRenderer</classname>.Gtk::DrawingArea myArea;
Cairo::RefPtr&lt;Cairo::Context&gt; myContext = myArea.get_window()-&gt;create_cairo_context();
myContext-&gt;set_source_rgb(1.0, 0.0, 0.0);
myContext-&gt;set_line_width(2.0);Gtk::Entry* entry = m_Combo.get_entry();
if (entry)
{
  // The Entry shall receive focus-out events.
  entry-&gt;add_events(Gdk::FOCUS_CHANGE_MASK);

  // Alternatively you can connect to m_Combo.signal_changed().
  entry-&gt;signal_changed().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_entry_changed) );

  entry-&gt;signal_activate().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_entry_activate) );

  entry-&gt;signal_focus_out_event().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_entry_focus_out_event) );
}Gtk::EventBox();Gtk::Label soporta formateado simple, por ejemplo, permitiéndole hacer que el texto se vea en negrita, coloreado, o más grande. Puede hacer esto proporcionándole una cadena a <methodname>set_markup()</methodname>, usando la <ulink url="http://developer.gnome.org/pango/unstable/PangoMarkupFormat.html">sintaxis de marcado de Pango</ulink>. Por ejemplo, <code> &lt;b&gt;texto en negrita&lt;/b&gt; y &lt;s&gt;texto tachado&lt;/s&gt; </code> .Gtk::TreeModel::Children children = row.children();Gtk::TreeModel::Row row = *iter;Gtk::TreeModel::Row row = m_refModel-&gt;children()[5]; //The fifth row.
if(row)
  refTreeSelection-&gt;select(row);Gtk::TreeModel::iterator iter = m_Combo.get_active();
if(iter)
{
  Gtk::TreeModel::Row row = *iter;

  //Get the data for the selected row, using our knowledge
  //of the tree model:
  int id = row[m_Columns.m_col_id];
  set_something_id_chosen(id); //Your own function.
}
else
  set_nothing_chosen(); //Your own function.Gtk::TreeModel::iterator iter = m_refListStore-&gt;append();Gtk::TreeModel::iterator iter = m_refModel-&gt;children().begin()
if(iter)
  refTreeSelection-&gt;select(iter);Gtk::TreeModel::iterator iter_child =
    m_refTreeStore-&gt;append(row.children());Gtk::TreeView::Column* pColumn =
  Gtk::manage(new Gtk::TreeView::Column("Icon Name"));

// m_columns.icon and m_columns.iconname are columns in the model.
// pColumn is the column in the TreeView:
pColumn-&gt;pack_start(m_columns.icon, /* expand= */ false);
pColumn-&gt;pack_start(m_columns.iconname);

m_TreeView.append_column(*pColumn);Gtk::TreeView::Column* pColumn = treeview.get_column(0);
if(pColumn)
  pColumn-&gt;set_sort_column(m_columns.m_col_id);Gtk::Widget* pMenubar = m_refUIManager-&gt;get_widget("/MenuBar");
pBox-&gt;add(*pMenuBar, Gtk::PACK_SHRINK);Gtk::Window window;
window.set_default_size(200, 200);Archivos de código fuente programados a manoEscribir constructores a manoManeje las opciones en <function>main()</function> y ocúltelas de <classname>Gtk::Application</classname> estableciendo <literal>argc = 1</literal> en la llamada a <methodname>Gtk::Application::create()</methodname>.Manejar <literal>button_press_event</literal>Cabeceras y enlazadoHello WorldHola mundo 2«Hola mundo» en <application>gtkmm</application>HelloWorld::HelloWorld()
:
  m_button ("Hello World")
{
  set_border_width(10);
  m_button.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;HelloWorld::on_button_clicked));
  add(m_button);.
  m_button.show();
}Algunos ejemplos de gestión normal de la memoria en C++:Aquí hay una lista de estos widgetsAquí hay un ejemplo simple que incluye 100 botones conmutadores en una ventana ScrolledWindow. Intente redimensionar la ventana para ver reaccionar a las barras de desplazamiento.Aquí hay un poco de código que junta todo: (tenga en cuenta que normalmente no cargaría la imagen cada vez en el manejador de señal de dibujo. Se muestra aquí sólo para mantener a todo junto).Aquí hay un ejemplo muy simple, demostrando arrastrar y soltar en una operación de <literal>copia</literal>:Aquí hay un ejemplo de un método de retorno de llamada:Aquí hay un ejemplo de un programa que dibuja texto, parte de él invertido. El capítulo de impresión contiene otro <link linkend="sec-printing-example">ejemplo</link> de dibujo de texto.Aquí hay un ejemplo de un programa simple que dibuja una imagen.Aquí hay un extracto de una sesión de <application>gdb</application>. Sólo se muestran las partes más interesantes de la salida. <placeholder-1/> Puede ver que la excepción se lanzó desde <filename>without_signal.cc</filename>, en la línea 6 (<code>throw "Something";</code>).Aquí hay algo de código de ejemplo de <filename>gtkmm/demos/gtk-demo/example_icontheme.cc</filename>, que tiene un icono pixbuf y un nombre de texto en la misma columna:Aquí está el código fuente del ejemplo que produjo las capturas de pantalla anteriores. Cuando ejecute este ejemplo, proporcione un número entre 1 y 3 como opción de línea de comandos, para ver las diferentes opciones de empaquetado en acción.Aquí se define una clase nueva llamada <classname>OverridenButton</classname>, que hereda de <classname>Gtk::Button</classname>. Lo único que se cambia es el método <methodname>on_clicked()</methodname>, que se llama siempre que <classname>Gtk::Button</classname> emite la señal <literal>clicked</literal>. Este método imprime «Hello World» a <literal>stdout</literal> y después llama al método original, reemplazado, para dejarle a <classname>Gtk::Button</classname> hacer lo que hubiera hecho si no se hubiera reemplazado.Un ejemplo sencillo: <placeholder-1/>Aquí hay un ejemplo ligeramente más amplio de los «slots» en acción:Aquí hay un ejemplo de un <classname>SpinButton</classname> en acción:Aquí hay un ejemplo de un manejador de señales que se conecta a una señal:Aquí hay un programa simple de ejemplo que dibuja un arco, un círculo, y una elipse en un área de dibujo.Un ejemplo de esta técnica:Aquí está el constructor del widget <classname>Box</classname>, y métodos que establecen opciones de empaquetado por contenedor: <placeholder-1/> Pasarle <literal>true</literal> a <parameter>set_homogeneous()</parameter> hará que todos los widgets contenidos sean del mismo tamaño. <parameter>spacing</parameter> es el número (mínimo) de píxeles que dejar entre cada widget.Cómo funciona gettextCómo usar Git para traductores de GNOMESin embargo, <application>Glib</application> define macros de soporte de <function>gettext()</function> que son contenedores más pequeños en una forma fácil de usar. Para usar estas macros, incluya <literal>&lt;glibmm/i18n.h&gt;</literal>, y luego, por ejemplo, substituya <placeholder-1/> con: <placeholder-2/>Sin embargo, hay que tener cuidado cuando se escriben programas basados en <application>gtkmm</application> usando múltiples hilos de ejecución, dado que <application>libsigc++</application>, y en particular <classname>sigc::trackable</classname>, no son seguras con hilos. Eso es porque ninguna de las complejas interacciones que ocurran internamente cuando usa <application>libsigc++</application> están protegidas por una exclusión mutua u otros métodos de sincronización. <placeholder-1/>Sin embargo, esto no le permite ningún control acerca de qué elementos pueden arrastrarse, ni dónde pueden soltarse. Si necesita ese control adicional, puede crear un <literal>Gtk::TreeModel</literal> derivado de <literal>Gtk::TreeStore</literal> o <literal>Gtk::ListStore</literal> y sobrecargar los métodos virtuales <literal>Gtk::TreeDragSource::row_draggable()</literal> y <literal>Gdk::TreeDragDest::row_drop_possible()</literal>. Puede examinar los <literal>Gtk::TreeModel::Path</literal> proporcionados y permitir o no arrastrar y soltar devolviendo <literal>true</literal> o <literal>false</literal>.Sin embargo, es aún más simple cuando se utiliza la macro <function>PKG_CHECK_MODULES()</function> en un archivo estándar configure.ac con autoconf y automake. Por ejemplo: <placeholder-1/> Esto comprueba la presencia de gtkmm y define MYAPP_LIBS y MYAPP_CFLAGS para su uso en los archivos Makefile.am.Sin embargo, tal vez no quiera que se almacenen los valores nuevos inmediatamente. Por ejemplo, tal vez quiera restringir la entrada a ciertos caracteres o rangos de valores.Sin embargo, probablemente ya evite matrices char* simples y aritmética de punteros usando <classname>std::string</classname>, por lo que sólo necesita comenzar a usar <classname>Glib::ustring</classname> en su lugar. Consulte el capítulo <link linkend="sec-basics-ustring">Conceptos básicos</link> acerca de <classname>Glib::ustring</classname>.I've been embedded.
A plug was addedINTLTOOL_FILES = intltool-extract.in \
                 intltool-merge.in \
                 intltool-update.inIT_PROG_INTLTOOL([0.35.0])

GETTEXT_PACKAGE=programname
AC_SUBST(GETTEXT_PACKAGE)
AC_DEFINE_UNQUOTED([GETTEXT_PACKAGE], ["$GETTEXT_PACKAGE"],
                   [The domain to use with gettext])
AM_GLIB_GNU_GETTEXT

PROGRAMNAME_LOCALEDIR=[${datadir}/locale]
AC_SUBST(PROGRAMNAME_LOCALEDIR)IdealLo ideal sería que <ulink url="http://www.gtkmm.org/bugs.shtml">proporcionara un parche</ulink> al archivo <filename>docs/tutorial/C/gtkmm-tutorial-in.xml</filename>. Este archivo está actualmente en el módulo <literal>gtkmm-documentation</literal> en el git de GNOME.Funciones en esperaSi un objeto de clase particular deriva de <classname>sigc::trackable</classname>, solo un hilo debe crear objetos <classname>sigc::slot</classname> representando cualquiera de los métodos no estáticos de la clase llamando a <function>sigc::mem_fun()</function>. El primer hilo que cree un «slot» semejante debe considerarse dueño del objeto relevante con el propósito de crear más «slots» referenciando a <emphasis>cualquiera</emphasis> de sus métodos no estáticos que usan esa función, o anulando aquellos «slots» desconectándolos o destruyendo el objeto «trackable».Si un programador no necesita un widget de alcance de clase, un widget de alcance de función también puede usarse. Las ventajas del alcance de función sobre el alcance de clase consisten en una mayor cantidad de datos ocultos y menos dependencias. <placeholder-1/>Si un programador no necesita asignación dinámica de memoria, puede usar los widgets automáticos en el alcance de clase. Una ventaja de los widgets automáticos en el alcance de clase es que la gestión de la memoria se agrupa en un único lugar. El programador no se arriesga a fugas de memoria por no <literal>eliminar</literal> un widget.Si todo funcionó correctamente, podrá construir <application>gtkmm</application> y a todas sus dependencias desde git ejecutando <command>jhbuild build</command> (o, si no especificó <application>gtkmm</application> en la variable <varname>modules</varname>, con el comando <command>jhbuild build gtkmm</command>).Si, por alguna razón, el <classname>Socket</classname> no pudiera adjuntar el <classname>Plug</classname>, la ventana se vería más o menos así:Si la enum no es un <classname>GType</classname>, debe pasar un tercer parámetro «NO_GTYPE». Este es el caso cuando no hay una función <function>*_get_type()</function> para la enum de C, pero tenga cuidado: no sólo necesita incluir una cabecera adicional para esa función, también debe enviar un informe de error de la API de C porque todas las enums deben registrarse como GTypes.Si se atrapan muchas excepciones antes de la que interesa, este método puede ser tedioso. Puede automatizarse con los siguientes comandos de <application>gdb</application>. <placeholder-1/> Estos comandos imprimirán una traza inversa de cada <code>throw</code> y continuará. La traza inversa del último (o posiblemente del penúltimo) <code>throw</code> antes de que el programa se detenga, es la interesante.Si esta es la primera vez que usa un programa que utiliza el sistema de archivos recientes, el diálogo podría estar vacío. De lo contrario, debería mostrar la lista de documentos recientemente usados registrados por otras aplicaciones.Si está interesado o interesada en ayudar con el desarrollo de <application>gtkmm</application>, o arreglar un error en <application>gtkmm</application>, probablemente necesite construir la versión de desarrollo de <application>gtkmm</application>. Sin embargo, no debe instalar una versión de desarrollo sobre su versión estable. En su lugar, debe instalarla junto a su instalación de <application>gtkmm</application> existente, en una ruta separada.Si está usando <application>gettext</application> directamente, sólo puede marcar cadenas para traducir si están en el archivo de código fuente. Sin embargo, si usa <application>intltool</application>, puede marcar cadenas para traducir en una variedad de otros formatos de archivo, incluyendo archivos de IU de <application>Glade</application>, xml, <ulink url="http://standards.freedesktop.org/desktop-entry-spec/latest/">archivos .desktop</ulink> y muchos más. Por lo tanto, si ha diseñado parte de la IU de la aplicación en <application>Glade</application>, entonces también añada sus archivos <filename>.glade</filename> a la lista en <literal>POTFILES.in</literal>.Si llama a <methodname>Gtk::TreeView::set:reorderable</methodname>, entonces se podrán mover los elementos de su «TreeView» dentro del «TreeView» en sí. Esto se demuestra en el ejemplo <classname>TreeStore</classname>.Si copió el esqueleto del árbol de fuentes en mm-common y sustituyó los marcadores de posición, entonces ya tendrá archivos <filename>Makefile.am</filename> y <filename>Doxyfile.in</filename> apropiados. Con la configuración de construcción de mm-common, la lista de los archivos de entrada de Doxygen no se define en el archivo de configuración de Doxygen, sino que se pasa desde <command>make</command> a la entrada estándar de <command>doxygen</command>. La variable <varname>doc_input</varname> define la lista de archivos de entrada en el archivo <filename>Makefile.am</filename>.Si copia un <classname>RefPtr</classname>, por ejemplo <placeholder-1/>, o si lo pasa como argumento a un método o como tipo de retorno, entonces <classname>RefPtr</classname> hará todas las referencias necesarias para asegurarse de que la instancia no se destruirá hasta que el último <classname>RefPtr</classname> haya salido del alcance.Si decide contribuir, por favor envíe su contribución a la lista de correo de <application>gtkmm</application>, en <ulink url="mailto:gtkmm-list@gnome.org">&lt;gtkmm-list@gnome.org&gt;</ulink>. Además, tenga en cuenta que la totalidad de este documento es libre, y cualquier adición que proporcione también debe serlo. Esto significa que la gente debe poder usar cualquier porción de sus ejemplos en sus programas, y las copias de este documento (incluyendo su contribución) se pueden distribuir libremente.Si no quiere buscar un URI específico, sino obtener una lista de todos los elementos usados recientemente, <classname>RecentManager</classname> proporciona la función <methodname>get_items()</methodname>. El valor que devuelve esta función es un <classname>std::vector</classname> de todos los archivos usados recientemente. El siguiente código demuestra cómo puede obtener una lista de todos los archivos usados recientemente:Si ha creado una <classname>Tag</classname> y la ha añadido a la <classname>TagTable</classname>, podrá aplicarle esa etiqueta a parte del <classname>TextBuffer</classname>, para que una parte del texto se muestre con ese formato. Puede definir el inicio y el fin del rango de texto especificando <classname>Gtk::TextBuffer::iterator</classname>. Por ejemplo:Si le pasa <literal>true</literal> al método <methodname>set_activates_default()</methodname>, pulsar Intro en el <classname>Gtk::Entry</classname> activará el widget predeterminado para la ventana que contiene al <classname>Gtk::Entry</classname>. Esto es especialmente útil en cuadros de diálogo. El widget predeterminado es generalmente uno de los botones del diálogo, que, por ejemplo, cerrará el cuadro de diálogo. Para establecer un widget como predeterminado, use <methodname>Gtk::Widget::set_can_default()</methodname> y <methodname>Gtk::Widget::grab_default()</methodname>.Si comparte un objeto de ajuste entre una barra de desplazamiento y un widget «TextView», manipular la barra de desplazamiento ajustará automágicamente al widget «TextView». Puede establecerlo así:Si intenta dibujar líneas de un píxel de anchura, notará que a veces la línea sale más borrosa y ancha de lo que debería. Esto sucede porque Cairo intentará dibujar desde la posición seleccionada, a ambos lados (mitad a cada uno), por que lo que si está posicionado justo en la intersección de los píxeles, y quiere líneas de un píxel de anchura, Cairo intentará usar la mitad de cada píxel adyacente, lo que no es posible (un píxel es la menor unidad posible). Esto sucede cuando la anchura de la línea es un número impar de píxeles (no sólo uno).Si quiere ayudar al desarrollo de <application>gtkmm</application> o experimentar con nuevas características, puede instalar <application>gtkmm</application> desde git. La mayoría de los usuarios nunca tendrán que hacer esto, pero si está interesado en involucrarse directamente con el desarrollo de <application>gtkmm</application>, consulte el apéndice <link linkend="chapter-working-with-source">Trabajando con el código fuente de gtkmm</link>.Si quiere registrar un archivo con metadatos, puede pasar un parámetro <classname>RecentManager::Data</classname> al <methodname>add_item()</methodname>. Los metadatos que pueden establecerse en un elemento archivo particular son los siguientes:Si quiere especificar un método que se llame cuando no está sucediendo nada más, use lo siguiente:Si quiere aprender más acerca de punteros inteligentes, puede echarle un vistazo a estos libros: <placeholder-1/>Si ha dibujado una serie de líneas que forman un camino, tal vez quiera que se junten de alguna manera. Cairo le ofrece tres maneras distintas de juntar líneas: «Miter», «Bevel», y «Round». Se muestran a continuación:Si nunca ha usado un kit de herramientas de empaquetado antes, puede llevar algo de tiempo acostumbrarse a él. Probablemente encuentre, sin embargo, que no necesita editores de formularios visuales tanto como con otros kits de herramientas.Si su distribución no proporciona un paquete <application>gtkmm</application> pre-construido, o si desea instalar una versión diferente a la proporcionada por su distribución, también puede instalar <application>gtkmm</application> desde las fuentes. El código fuente para <application>gtkmm</application> se puede descargar desde <ulink url="http://www.gtkmm.org/"/>.Si su programa es software libre, entonces hay todo un subproyecto de <literal>GNOME</literal> dedicado a ayudarle a hacer traducciones, el <ulink url="https://live.gnome.org/TranslationProject/">Proyecto de traducción de <literal>GNOME</literal></ulink>.Implementación de la lógica personalizada para celdas editables.En <filename>configure.ac</filename>, <placeholder-1/>En <filename>skeleton/skeletonmm/Makefile.am</filename> se deben mencionar los valores correctos de las variables genéricas que se usan en otros lados en el sistema de construcción:En <filename>skeleton/src/Makefile.am</filename> se deben mencionar los valores correctos para las variables genéricas que se usan en otros lados en el sistema de construcción:Además de añadir elementos a la lista, puede buscarlos y modificarlos o eliminarlos.Además de cambiar el URI de un archivo, también puede eliminar archivos de la lista uno a uno o todos juntos. Realice lo primero con <methodname>remove_item()</methodname>, y lo último con <methodname>purge_items()</methodname>.Además de dibujar líneas rectas básicas, también puede personalizar algunas cosas de las líneas. Ya ha visto ejemplos de cómo establecer el color y anchura de una línea, pero también hay otras cosas.Además de dibujar líneas rectas, Cairo le permite dibujar líneas curvas fácilmente. (técnicamente, una spline cúbica de Bézier) usando las funciones <methodname>Cairo::Context::curve_to()</methodname> y <methodname>Cairo::Context::rel_curve_to()</methodname>. Estas funciones toman las coordenadas de un punto de destino y de dos puntos de «control». Esto se entiende mejor con un ejemplo, así que analícelo en profundidad.En general, los proyectos de gtkmm usan Doxygen, que lee comentarios de C++ con un formato específico y genera documentación HTML. Puede escribir estos comentarios de Doxygen directamente en los archivos de cabecera.En la <classname>Gtk::Window</classname>, también está la sobrecarga del manejador predeterminado (<methodname>on_key_release_event()</methodname>), y otro manejador que se llama antes del predeterminado (<methodname>windowKeyReleaseBefore()</methodname>).En la sección <link linkend="sec-wrapping-hg-files">archivos .hg y .ccg</link> puede aprender acerca de la sintaxis usada en estos archivos.En el ejemplo anterior, se ha dibujado todo usando coordenadas absolutas. También puede dibujar usando coordenadas relativas. Para una línea recta, esto se hace con la función <methodname>Cairo::Context::rel_line_to()</methodname>.En las instrucciones a continuación se asumirá que no usará <application>gettext</application> directamente, sino <application>intltool</application>, que se ha escrito específicamente para <literal>GNOME</literal>. <application>intltool</application> usa <function>gettext</function>, que extrae cadenas del código fuente, pero <application>intltool</application> también puede combinar cadenas de otros archivos, por ejemplo desde los detalles del menú del escritorio y archivos de recursos de la IGU como archivos <application>Glade</application>, en archivos <application>gettext</application><filename>.pot/.po</filename> estándar.En el Makefile.am de nivel superior: <placeholder-1/>En estos casos, debe agregar caracteres adicionales a las cadenas. Por ejemplo, use <literal>"jumps[noun]"</literal> y <literal>"jumps[verb]"</literal> en lugar de sólo <literal>"jumps"</literal> y límpielas de nuevo fuera de la llamada a <function>gettext</function>. Si añade caracteres adicionales también debe añadir un comentario para los traductores antes de la llamada a <function>gettext</function>. Tales comentarios se mostrarán en los archivos <filename>.po</filename>. Por ejemplo:En este ejemplo hay tres manejadores de eventos que se llaman después del manejador de eventos predeterminado de <classname>Gtk::Window</classname>, uno en la <classname>Gtk::Entry</classname>, uno en el <classname>Gtk::Grid</classname> y uno en la <classname>Gtk::Window</classname>.En este ejemplo hay tres combinaciones de teclas: <keycap>Alt</keycap>+<keycap>1</keycap> selecciona el primer botón de radio, <keycap>Alt</keycap>+<keycap>2</keycap> selecciona el segundo, y la tecla <keycap>Escape</keycap> oculta (cierra) la ventana. El manejador de eventos predeterminado se sobrecarga, como se describe en la sección <link linkend="sec-overriding-default-signal-handlers">Sobrecargar los manejadores de señales predeterminados</link> en el apéndice.En este ejemplo, se construirá un programa <application>gtkmm</application> pequeño pero funcional y se dibujarán algunas líneas en la ventana. Las líneas se dibujan creando un camino y luego rellenándolo. Un camino se crea usando las funciones <methodname>Cairo::Context::move_to()</methodname> y <methodname>Cairo::Context::line_to()</methodname>. La función <methodname>move_to()</methodname> es similar al acto de levantar el bolígrafo del papel y ponerlo en algún otro lado: no se dibuja ninguna línea entre el punto en el que estaba y el punto al que se movió. Para dibujar una línea entre dos puntos, use la función <methodname>line_to()</methodname>.En esta sección del tutorial, se cubrirá el modelo básico de dibujo con Cairo, describiendo cada uno de los elementos básicos de dibujo (con ejemplos), y luego se prsentará una aplicación simple que usa Cairo para dibujar un widget de reloj personalizado.En su <literal>src/Makefile.am</literal>, actualice su <literal>AM_CPPFLAGS</literal> para añadir la siguiente definición de macro de preprocesador:En su retorno de llamada, compare la lista de objetivos disponibles con aquellos que su aplicación soporta pegar. Puede activar o no el elemento en el menú «pegar», dependiendo de si pegar es posible o no actualmente. Por ejemplo:En su manejador de señales, debe examinar el valor nuevo y luego almacenarlo en el modelo, si eso es lo apropiado para su aplicación.Incluye a los otros archivos.Vistas ordenadas independientemente del mismo modeloInfoBarSe puede hacer uso de herencia para derivar nuevos widgets. Derivar nuevos widgets en código C GTK+ es tan complicado y propenso a errores que casi ningún codificador de C lo hace. Como programador en C++ usted sabe que la derivación es una técnica orientada a objetos esencial.InicializaciónInstalaciónInstalar <application>gtkmm</application> con <application>jhbuild</application>Instalar desde las fuentesInstalar y utilizar la versión de git de <application>gtkmm</application>En lugar de conectar manejadores de señales a señales laboriosamente, puede simplemente hacer una clase nueva que herede de un widget (por ejemplo, un botón) y luego reemplazar el manejador de señales predeterminado, como Button::on_clicked(). Esto puede ser mucho más simple que enganchar manejadores de señales para todo.Tipos intermediosInternacionalización y localizaciónInternacionalizar aplicaciones de GNOMEREADME de intltoolIntroducciónTambién toma un argumento opcional adicional: <placeholder-1/>Sigue la misma forma. El número 3 al final del nombre del tipo indica que el manejador de señales necesitará tres argumentos. El primer tipo en la lista es <type>void</type>, por lo que ese será el tipo que devolverá el manejador de señales. Los tres tipos siguientes son los de los argumentos, en orden. El prototipo de manejador de señales se podría ver así:Es común cuando se enlazan módulos rastrear el número de versión de la biblioteca que se está envolviendo. Entonces, por ejemplo, si la biblioteca de C está en una versión 1.23.4, el número de versión inicial del módulo de enlace sería 1.23.0. Sin embargo, evite comenzar con un número de versión menor par, ya que generalmente indica una versión estable.Es una buena práctica poner todas las modificaciones al estado de gráficos entre llamadas a función <methodname>save()</methodname>/<methodname>restore()</methodname>. Por ejemplo, si tiene una función que toma una referencia a <classname>Cairo::Context</classname> como argumento, puede implementarlo como sigue:Soporta pegar dos objetivos: tanto el personalizado como el de texto que crea una representación de texto arbitraria de los datos personalizados.Usa <methodname>request_targets()</methodname> y la señal <literal>owner_change</literal>, y desactiva el botón «pegar» si no puede usar nada en el portapapeles.Es imposible predecir la cantidad de espacio necesaria para texto después de que se ha traducido a otros idiomas, o se ha mostrado en otra tipografía. En Unix, también es imposible anticipar los efectos de cada tema y gestor de ventanas.Es posible que ciertas cadenas se marquen como <literal>fuzzy</literal> en el archivo <filename>.po</filename>. Estas traducciones no sustituirán la cadena original. Para hacerlas aparecer, simplemente elimine la etiqueta <literal>fuzzy</literal>.Iterar sobre las filas del modeloIteradoresJonathonJongsmaSólo llama a la versión no constante de la misma función, en lugar de generar código casi duplicado.Al igual que con los punteros normales, puede verificar si un <classname>RefPtr</classname> apunta a algo.Eventos de tecladoEventos de teclado: propagación de eventosEventos del teclado: simpleKingKjellEtiquetaLas etiquetas son el método principal para poner texto no editable en ventanas, por ejemplo, para poner un título junto a un widget <classname>Entry</classname>. Puede especificar el texto en el constructor, o más tarde con los métodos <methodname>set_text()</methodname> o <methodname>set_markup()</methodname>.Falta de propiedadesLaursenSe requiere menos código en C++.Eche un vistazo a un ejemplo de reemplazo:Eche un vistazo a un <literal>helloworld</literal> ligeramente mejorado, mostrando lo que ha aprendido.Eche otro vistazo al método <literal>connect</literal> de la señal:Al igual que las casillas de verificación, los botones de radio también heredan de <classname>Gtk::ToggleButton</classname>, pero trabajan en grupos, y sólo se puede seleccionar un un botón de radio en un grupo a la vez.Al igual que con el <classname>TreeView</classname>, probablemente deba poner su <classname>TextView</classname> dentro de una <classname>ScrolledWindow</classname> para permitirle al usuario ver y mover toda el área de texto con barras de desplazamiento.De la misma manera, reemplace todas las instancias de <varname>Joe Hacker</varname> por el nombre del titular de los derechos de autor, quien probablemente sea usted. Haga lo mismo para la dirección de correo-e <varname>joe@example.com</varname>.Las puntas de las líneas pueden también tener distintos estilos. El estilo predeterminado consiste en que la línea comience y se detenga exactamente en sus puntos de destino. Esto se llama terminación «Butt». Las otras opciones son «Round» (usa una terminación redondeada, con el centro del círculo en el último punto) o «Square» (usa una terminación cuadrada, con el centro del cuadrado en el último punto). Esta opción se establece usando la función <methodname>Cairo::Context::set_line_cap()</methodname>.Estilos de líneaListStoreListStore, para filasCargar el archivo .gladeBuscar elementos en la lista de archivos recientesMucha gente necesita implementar menús contextuales del botón derecho para los <classname>TreeView</classname>, por lo que se explicará cómo hacerlo para ahorrarle tiempo. Excepto uno o dos puntos, es muy parecido a un menú contextual normal, tal como se describe en el <link linkend="sec-menus-popup">capítulo acerca de menús</link>.Menú principalEjemplo de menú principalArchivos Makefile.amWidgets gestionadosMuchas funciones de dibujo de Cairo tienen una variante <methodname>_preserve()</methodname>. Normalmente, las funciones de dibujo como <methodname>clip()</methodname>, <methodname>fill()</methodname>, o <methodname>stroke()</methodname> despejarán el camino actual. Si usa la variante <methodname>_preserve()</methodname>, el camino actual se retendrá, por lo que podrá usar el mismo camino con la próxima función de dibujo.Muchos conjuntos de herramientas de la IGU le requieren ubicar precisamente widgets en una ventana, utilizando posicionamiento absoluto, a menudo usando un editor visual. Esto lleva a muchos problemas:Marcar cadenas para traducirMarkoMarcasTal vez, el usuario no deba ser capaz de seleccionar todos los elementos en su lista o árbol. Por ejemplo, en gtk-demo, puede seleccionar una demostración para ver su código fuente, pero no tiene ningún sentido seleccionar una categoría de demostraciones.Pueden usarse instancias de miembros, simplificando la gestión de memoria. Todos los widgets C GTK+ son tratados usando punteros. Como programador en C++ usted sabe que los punteros deben evitarse siempre que sea posible.Gestión de la memoriaMenús y barras de herramientasMessageDialogMacros de métodosMétodosMicrosoft WindowsWidgets variosMezclando las API de C y C++Columnas del modeloModelColumns()
{ add(m_col_id); add(m_col_name); }

  Gtk::TreeModelColumn&lt;int&gt; m_col_id;
  Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
};

ModelColumns m_columns;Modificar archivos de construcciónModificar la lista de archivos recientesMonitorizar E/SSe presenta y demuestra más información sobre lo que subyace al proceso de internacionalización y localización en: <placeholder-1/>Más de una columna del modelo por columna de la vistaLa mayoría de las aplicaciones sólo tendrán una <classname>Window</classname>, o sólo una ventana principal. Estas aplicaciones pueden usar la sobrecarga <methodname>Gtk::Application::run(Gtk::Window&amp;)</methodname>. Muestra la ventana y vuelve cuando esta se ha ocultado. Esto puede suceder cuando el usuario la cierra, o cuando su código ejecuta <methodname>hide()</methodname> en ella. Puede evitar que el usuario cierre la ventana (por ejemplo, si hay cambios sin guardar) sobrecargando <methodname>Gtk::Window::on_delete_event()</methodname>.La mayoría de los widgets personalizados necesitan su propia <classname>Gdk::Window</classname> sobre la que dibujar. Después podrá llamar a <methodname>Gtk::Widget::set_has_window(true)</methodname> en su constructor (este es el valor predeterminado). Si no llama a <methodname>set_has_window(false)</methodname>, debe reemplazar a <methodname>on_realize()</methodname> y llamar a <methodname>Gtk::Widget::set_realized()</methodname> y a <methodname>Gtk::Widget::set_window()</methodname> desde allí.La mayoría de los ejemplos usan esta técnica.La mayoría de los capítulos de este libro tratan de widgets específicos. Consulte la sección <link linkend="chapter-container-widgets">Widgets contenedores</link> para obtener más detalles sobre de cómo agregar widgets a widgets contenedores.La mayoría de los métodos miembros útiles de esta clase están en realidad en la clase base <classname>Gtk::FileChooser</classname>.La mayor parte del empaquetado usa cajas como en el ejemplo anterior. Éstas son contenedores invisibles en los que podemos empaquetar a nuestros widgets. Cuando se empaquetan los widgets en una caja horizontal, los objetos se insertan horizontalmente de izquierda a derecha o de derecha a izquierda dependiendo de si se usó <methodname>pack_start()</methodname> o <methodname>pack_end()</methodname>. En una caja vertical, los widgets se empaquetan de arriba a abajo o viceversa. Puede usar cualquier combinación de cajas dentro o al lado de otras cajas para crear el efecto deseado.MoverPrograma con múltiples hilosProgramas con múltiples hilosWidgets de elementos múltiplesLos widgets de elementos múltiples heredan de <classname>Gtk::Container</classname>; al igual que con <classname>Gtk::Bin</classname>, use los métodos <methodname>add()</methodname> y <methodname>remove()</methodname> para añadir y eliminar widgets contenedores. A diferencia de <methodname>Gtk::Bin::remove()</methodname>, sin embargo, el método <methodname>remove()</methodname> para <classname>Gtk::Container</classname> toma un argumento, especificando qué widget eliminar.MurrayMurray CummingA continuación, llamamos al método <methodname>set_border_width()</methodname> de la ventana. Esto establece el tamaño del espacio entre los lados de la ventana y el widget que contiene.A continuación se deben adaptar los archivos <filename>Makefile.am</filename>: <placeholder-1/>A continuación debe crear un <classname>UIManager</classname> y añadirle el <classname>ActionGroup</classname> con <classname>insert_action_group()</classname>. En este punto, también es una buena idea decirle a la ventana madre que responda a los atajos del teclado especificados, usando <methodname>add_accel_group()</methodname>.A continuación usamos el método <methodname>add()</methodname> de la ventana para situar el <literal>m_button</literal> en ella. (<methodname>add()</methodname> deriva de <classname>Gtk::Container</classname>, que se describe en el capítulo sobre widgets contenedores). El método <methodname>add()</methodname> ubica al widget en la ventana, pero no lo muestra. Los widgets de <application>gtkmm</application> siempre son invisibles cuando se crean: para mostrarlos, debe llamar a su método <methodname>show()</methodname>, que es lo que se hace en la siguiente línea.Nicolai M. Josuttis, «The C++ Standard Library» - sección 4.2AboutDialog no modalGestión normal de la memoria en C++Tenga también en cuenta que no todos los widgets reciben todos los eventos de X de manera predeterminada. Para recibir eventos de X adicionales, puede usar <methodname>Gtk::Widget::set_events()</methodname> antes de mostrar al widget, o <methodname>Gtk::Widget::add_events()</methodname> después de haberlo mostrado. Sin embargo, algunos widgets deben ponerse dentro de un widget <classname>EventBox</classname> primero. Consulte el capítulo <link linkend="chapter-widgets-without-xwindows">Widgets sin X-Windows</link>.tenga en cuenta que UTF-8 no es compatible con codificaciones de 8 bits como ISO-8859-1. Por ejemplo, las diéresis alemanas no están en el rango ASCII y necesitan más de un byte en la codificación UTF-8. Si su código contiene cadenas literales de 8 bits, debe convertirlas a UTF-8 (por ejemplo, el saludo bávaro «Grüß Gott» sería «Gr\xC3\xBC\xC3\x9F Gott»).Tenga en cuenta que los archivos que terminan en <filename>.in</filename> se utilizan para generar archivos con el mismo nombre pero sin el sufijo <filename>.in</filename>, mediante la sustitución de algunas variables con valores reales durante la fase de configuración.Tenga en cuenta que si menciona módulos adicionales, además de gtkmm-3.0, deben estar separados por espacios, no por comas.Tenga en cuenta que, en este caso, se ha expresado casi todo en términos de anchura y altura de la ventana, incluyendo la anchura de las líneas. Es por esto que, cuando cambie el tamaño de la ventana, todo se escalará a ella. Además, tenga en cuenta que hay tres secciones de dibujo en la función, y cada una está envuelta en un par <methodname>save()</methodname>/<methodname>restore()</methodname> para volver a un estado conocido después de cada dibujo.Tenga en cuenta que la mayoría de los equipos de idiomas sólo constan de 1 a 3 personas, por lo que si su programa contiene muchas cadenas, puede pasar un tiempo antes de que alguien tenga el tiempo de echarle un vistazo. Además, la mayoría de los traductores no quieren perder el tiempo (traducir es una tarea que consume mucho) por lo que si no juzgan que su proyecto es realmente serio (en el sentido de que esté pulido y se mantenga) podrían decidir usar su tiempo en algún otro proyecto.Tenga en cuenta que la instancia (como m_Columns aquí) normalmente no debe ser estática, porque a menudo se necesita instanciarla después de haber instanciado a glibmm.Tenga en cuenta que no se le pasa un puntero a <methodname>on_button_clicked()</methodname> directamente al método de la señal <methodname>connect()</methodname>. En su lugar, se llama a <function>sigc::ptr_fun()</function>, y se le pasa el resultado a <methodname>connect()</methodname>.Tenga en cuenta que no puede simplemente hacer <placeholder-1/> porque se modifica al grupo mediante <methodname>set_group()</methodname>, y por lo tanto, no es constante.Tenga en cuenta que debe especificar acciones para submenús así como para elementos del menú.Tenga en cuenta que, debido a sistema de tema de GTK+, las apariencia de estos widgets variará. En el caso de las casillas y de los botones de radio, variará considerablemente.Tenga en cuenta, sin embargo, que el «TreeView» le proporcionará iteradores al modelo ordenado. Debe convertirlos a iteradores del modelo hijo subyacente para llevar a cabo acciones en ese modelo. Por ejemplo:CuadernoTenga en cuenta que se le proporcionó a <command>gmmproc</command> la ruta de los archivos de conversión .m4, la ruta del archivo .defs, el nombre de un archivo .hg, la carpeta de las fuentes, y la carpeta de destino.Tenga en cuenta que se ha usado una declaración de inicialización para darle al objeto <literal>m_button</literal> la etiqueta «Hello World».Tenga en cuenta que, después de haber cancelado un evento, no se llamará a ninguna otra función (incluso si es del mismo widget).Ahora eche un vistazo a la función <function>main()</function> del programa. Aquí está, sin comentarios:Ahora, mire la conexión nuevamente:Ahora vea qué pasa cuando una excepción se lanza desde un manejador de señales. Aquí está el código fuente. <placeholder-1/>Ahora, eche un vistazo al código que hace el dibujo en sí. La primera sección del <methodname>on_draw()</methodname> ya le debería resultar bastante familiar. Este ejemplo, otra vez, escala el sistema de coordenadas para ser un cuadrado unitario, así es más fácil dibujar el reloj como un porcentaje del tamaño de la ventana para que se escale automáticamente cuando el tamaño de la ventana se ajuste. Además, el sistema de coordenadas se escala de tal manera que la coordinada (0, 0) esté justo en el centro de la ventana.Ahora que hay un lugar en el que poner sus traducciones, necesita inicializar <application>intltool</application> y <application>gettext</application>. Añádale el siguiente código a su <literal>configure.ac</literal>, substituyendo «programname» con el nombre de su programa:Ahora que entiende lo básico sobre la biblioteca de gráficos Cairo, está casi listo para empezar a dibujar. Empezará con el elemento de dibujo más simple: la línea recta. Pero, primero necesita saber algo del sistema de coordenadas de Cairo. El origen del sistema de coordenadas de Cairo está en la esquina superior izquierda de la ventana, con valores positivos de x hacia la derecha y valores positivos de y hacia abajo. <placeholder-1/>Ahora que se ha cubierto lo básico acerca del dibujo con Cairo, junte todo y cree una aplicación simple que haga algo de verdad. El siguiente ejemplo usa Cairo para crear un widget <classname>Clock</classname> personalizado. El reloj tiene una manecilla de segundos, una de minutos, y una de horas; y se actualiza cada segundo.Ahora que ha visto señales y manejadores de señales en <application>gtkmm</application>, tal vez quiera usar la misma técnica para permitir interacción entre sus propias clases. Eso es realmente muy simple usando la biblioteca <application>libsigc++</application> directamente.Ahora se editan los archivos para adaptarlos a las necesidades. Tal vez prefiera usar una utilidad para buscar y reemplazar múltiples archivos, como <command>regexxer</command>. Tenga en cuenta que casi todos los archivos proporcionados con el esqueleto del árbol de fuentes contienen texto con marcadores de posición. Es por esto que las sustituciones se deben hacer globalmente, y no limitarse a los archivos de Automake y Autoconf.Hasta aquí está todo bien, pero ¿y si quiere crear sus propios manejadores para responder cuando el usuario ajusta un widget <classname>Range</classname> o un <classname>SpinButton</classname>? Para acceder al valor de un <classname>Gtk::Adjustment</classname>, puede usar los métodos <methodname>get_value()</methodname> y <methodname>set_value()</methodname>:Objetos y funciones.Objetos tales como <classname>Gdk::Pixbuf</classname> sólo pueden instanciarse con una función <methodname>create()</methodname>. Por ejemplo, <placeholder-1/>Objetos usados a través de <classname>RefPtr</classname>: pase el <classname>RefPtr</classname> como una referencia constante. Por ejemplo, <code>const Glib::RefPtr&lt;Gtk::FileFilter&gt;&amp; filter</code>.Ocasionalmente querrá definir un widget <classname>Entry</classname> como sólo lectura. Esto se puede hacer pasándole <literal>false</literal> al método <methodname>set_editable()</methodname>.Por supuesto esto significa que puede almacenar <classname>RefPtr</classname> en contenedores estándar, como <classname>std::vector</classname> o <classname>std::list</classname>.Por supuesto, un contenedor de nivel superior no se añadirá a otro contenedor. El programador es responsable de la destrucción del contenedor de nivel superior usando una de las técnicas tradicionales de C++. Por ejemplo, una ventana de nivel superior podría ser sólo una instancia en su función <function>main()</function>.Cuando se envuelven métodos, a menudo es deseable almacenar el valor que devuelve una función de C en lo que se conoce como parámetro de salida. En este caso, el método de C++ devuelve <type>void</type> pero se incluye en su lista de argumentos un parámetro de salida en el que se almacena el valor de la función de C. gmmproc permite esta funcionalidad, pero deben incluirse macros de inicialización apropiadas para decirle a gmmproc cómo inicializar el parámetro de C++ desde el valor de devolución de la función de C.OleEn Unix, el manejador de previsualización predeterminado usa un programa visor externo. En Windows, se mostrará el diálogo nativo de previsualización. Si es necesario, puede modificar este comportamiento y proporcionar un diálogo de previsualización personalizado. Consulte el ejemplo en /examples/book/printing/advanced.Una vez que haya construido su software, también necesitará ejecutar su programa dentro del entorno de jhbuild. Para hacerlo, puede usar de nuevo el comando <command>jhbuild shell</command> para arrancar un intérprete nuevo con el entorno de <application>jhbuild</application> configurado. Alternativamente, puede ejecutar un solo comando en el entorno de <application>jhbuild</application> usando el siguiente comando: <command>jhbuild run nombre-de-comando</command>. En este caso, el comando se ejecutará con las variables de entorno correctas establecidas, pero retornará a su entorno previo después de que el programa salga.Una vez que ha configurado <application>jhbuild</application> como se describió anteriormente, construir <application>gtkmm</application> debería ser relativamente directo. La primera vez que ejecute <application>jhbuild</application>, debe ejecutar la siguiente secuencia de comandos para asegurase que <application>jhbuild</application> tiene las herramientas adecuadas y verificar que está configurado correctamente: <screen>$ jhbuild bootstrap
$ jhbuild sanitycheck</screen>Uno de los beneficios de UTF-8 es que no necesita usarlo a menos que quiera, por lo que no necesita reconvertir todo su código de una vez. <classname>std::string</classname> todavía funcionará para cadenas de 7 bits ASCII. Pero cuando intente localizar su aplicación para lenguajes como chino, por ejemplo, empezará a ver errores extraños y posibles fallos. Entonces, todo lo que necesitará hacer es empezar a utilizar <classname>Glib::ustring</classname> en su lugar.Una de las mayores ventajas de <application>gtkmm</application> es que es multiplataforma. Los programas de <application>gtkmm</application> escritos en otras plataformas como GNU/Linux generalmente pueden transferirse a Windows (y viceversa) con pocas modificaciones al código fuente.Openismus tiene más <ulink url="http://www.openismus.com/documents/linux/automake/automake.shtml">ayuda básica con automake y autoconf</ulink>Procesado de parámetros opcionalesO puede especificar la etiqueta cuando inserta el texto por primera vez: <placeholder-1/>Otras macrosOtras macros, como <function>_WRAP_METHOD()</function> y <function>_WRAP_SIGNAL()</function> sólo pueden usarse después de una llamada a una macro <function>_CLASS_*</function>.Aparte del nombre de la señal (<literal>focus</literal>), hay otras dos cosas importantes que tener en cuenta aquí: el número que sigue a la palabra <classname>SignalProxy</classname> en el principio (1, en este caso), y los tipos en la lista (<type>bool</type> y <type>Gtk::DirectionType</type>). El número indica cuántos argumentos debe tener el manejador de señales; el primer tipo, <type>bool</type>, es el tipo que el manejador de señales debe devolver; y el tipo siguiente, <type>Gtk::DirectionType</type>, es el tipo del primer y único argumento de esta señal. Mirando la documentación de referencia, también puede ver los nombres de los argumentos.Todos los ejemplos tienden a tener la misma estructura. Siguen estos pasos para usar un <classname>widget</classname>:Procesado de parámetros de salidaReemplazar manejadores de señales predeterminadosVista generalPKG_CHECK_MODULES([MYAPP], [gtkmm-3.0 &gt;= 3.8.0])Empaquete al widget en un contenedor usando la llamada apropiada, por ejemplo, <methodname>Gtk::Container::add()</methodname> o <methodname>pack_start()</methodname>.EmpaquetadoConfiguración de páginaCon panelesSe pueden usar paneles para dividir un widget en dos mitades, separadas por un divisor móvil. Las dos mitades (paneles) pueden orientarse tanto horizontal (lado a lado) como verticalmente (uno encima de otro).PangoReordenación de parámetrosPartes del capítulo acerca de «Internacionalización».Partes de la actualización de gtkmm 2 a gtkmm 3.PegarPedroOpciones de empaquetado por hijoOpciones de empaquetado por contenedorSe otorga permiso para copiar, distribuir y/o modificar este documento en virtud de los términos de la Versión 1.2 de la Licencia de Documentación Libre de GNU o de cualquier versión posterior publicada por la Fundación para el Software Libre; sin Secciones Invariantes, sin Textos de Portada y sin Textos de Contraportada. Puede conseguir una copia de la Licencia de Documentación Libre de GNU, visitando la página oficial o escribiendo a: Free Software Fundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, EE. UU.Errores comunesConsulte <ulink url="http://live.gnome.org/gtkmm/MSWindows/BuildingGtkmm">http://live.gnome.org/gtkmm/MSWindows/BuildingGtkmm</ulink> para obtener instrucciones sobre cómo construir gtkmm en Windows.«Plugs»«Plugs» y «Sockets»Ejemplo de «Plugs» y «Sockets».Menú contextual emergenteMenú emergenteEjemplo de menú emergenteMenús emergentesPaquetes preconstruidosPreparar su proyectoFascinante, ¿verdad? Examinemos el código. Primero, la clase <classname>HelloWorld</classname>:Evitar la selección de la filaVista previaPrintOperationImpresiónImpresión simpleProbablemente la manera más común de crear un <classname>Gdk::Pixbuf</classname> es usar <methodname>Gdk::Pixbuf::create_from_file()</methodname>, que puede leer un archivo de imagen, como un archivo png, hacia un «pixbuf» listo para procesar.Problemas en la API de C.Programar con <application>gtkmm</application> 3Las barras de progreso se usan para mostrar el estado de una operación en curso. Por ejemplo, una <classname>ProgressBar</classname> puede mostrar cuánto se ha completado de una tarea.ProgressBarPulsadoresPone el código generado en bloques #ifdef.Pone el código generado en bloques #ifdef. El texto que explica por qué se marca como obsoleto puede especificarse como un parámetro opcional.Botones de radioBotón de radioWidgets de RangoAcerca de reemplazar manejadores de señales: puede hacer esto en el mundo de C plano de GTK+, también; para eso existe el sistema de objetos de GTK+. Pero en GTK+, hay que realizar algunos procedimientos complicados para obtener características orientadas a objetos como herencia y sobrecarga. En C++, es simple, dado que esas características se soportan en el lenguaje en sí; puede dejarle el trabajo pesado al compilador.Las versiones recientes de <application>gtkmm</application> se empaquetan en casi todas las distribuciones principales de Linux actualmente. Si usted utiliza Linux, es probable que pueda empezar a trabajar con <application> gtkmm </application> instalando el paquete desde el repositorio oficial para su distribución Linux. Las distribuciones que cuentan con <application>gtkmm</application> en sus repositorios son Debian, Ubuntu, Red Hat, Fedora, Mandriva, Suse, y muchas otras.RecentChooserRecentManagerDocumentos usados recientementeTécnicas recomendadasReferenciaRecuerde que en un sistema Unix o Linux, probablemente tendrá que ser <literal>root</literal> para instalar el software. Los comandos <command>su</command> o <command>sudo</command> le permitirán introducir la contraseña de <literal>root</literal>para tener el acceso de <literal>root</literal> temporalmente.Recuerde que estos nombres son sólo identificadores que se usaron cuando se crearon las acciones. No son el texto que el usuario verá en los menús y barras de herramientas. Se han proporcionado esos nombres legibles por el humano cuando se crearon las acciones.Recuerde que no está instanciando un widget con <methodname>get_widget()</methodname>, sólo está obteniendo un puntero a uno que ya existe. Siempre recibirá un puntero a la misma instancia cuando llame a <methodname>get_widget()</methodname> en el mismo <classname>Gtk::Builder</classname> con el mismo nombre de widget. Los widgets se instancian durante <methodname>Gtk::Builder::create_from_file()</methodname>.Renderizar textoFilas reordenablesRecursosResponder a los cambiosReutilizar la documentación de CRiederFila hijaMismas cadenas, semánticas diferentesWidgets de EscalaWidgets de barras de desplazamientoLas ventanas desplazables tienen <emphasis>políticas de desplazamiento</emphasis> que determinan si se muestran las <classname>Scrollbar</classname> o no. Las políticas se pueden establecer mediante el método <methodname>set_policy()</methodname>. La política puede ser <literal>Gtk::POLICY_AUTOMATIC</literal> o <literal>Gtk::POLICY_ALWAYS</literal>. <literal>Gtk::POLICY_AUTOMATIC</literal> hace que la ventana desplazable muestre la barra de desplazamiento sólo si el widget contenido es más grande que el área visible. <literal>Gtk::POLICY_ALWAYS</literal> hace que la barra de desplazamiento se muestre siempre.ScrolledWindowDesplazamientoSegundo, comprobar si hay errores y conectar la señal <literal>status_changed</literal>. Por ejemplo: <placeholder-1/>Sección «Construir la estructura» del capítulo acerca de «Envolver bibliotecas de C con gmmproc».Sección acerca de Gtk::Grid.Consulte <link linkend="sec-printing-example-simple">un ejemplo</link> de cómo realizar esto exactamente. Consulte el capítulo <link linkend="chapter-draganddrop">Arrastrar y soltar</link> para obtener información general acerca de arrastrar y soltar con gtkmm.Para obtener más información acerca de cómo proporcionar cadenas literales UTF-8, consulte la sección <link linkend="chapter-internationalization">Internacionalización</link>.Consulte el <link linkend="chapter-refptr">apéndice</link> para obtener información detallada acerca de «RefPtr».Consulte la sección <link linkend="sec-progressbar">ProgressBar</link> para ver otro ejemplo que usa un <classname>Alignment</classname>.Seleccionar qué tipos de C++ deben usarse también es importante cuando se envuelve una API de C. A pesar de que generalmente es obvio qué tipos de C++ deben usarse en el método de C++, aquí hay algunos consejos: <placeholder-1/>Establezca los atributos del widget. Si el widget no tiene un constructor predeterminado, tendrá que inicializar el widget en la lista inicializadora del constructor de su clase contenedora.Establezca el título de la pestaña mediante <methodname>PrintOperation::set_custom_tab_label()</methodname>, cree un widget nuevo y devuélvalo desde el manejador de señales <literal>create_custom_widget</literal>. Probablemente quiera que este sea un widget contenedor, empaquetado con algunos otros.Establecer un prefijoConfigurar JHBuildConfigurar los valoresRecursos compartidosSe muestra a continuación un ejemplo simple de cómo usar las clases <classname>RecentChooserDialog</classname> y <classname>RecentAction</classname> en un programa. Este programa simple tiene una barra de menú con un elemento de menú <guimenuitem>Recent Files Dialog</guimenuitem>. Cuando seleccione este elemento, aparecerá un diálogo mostrando la lista de archivos recientemente usados.Secuencia de los manejadores de señalesSeñalesSeñales y propiedades.Las señales generalmente tienen punteros de funciones en la estructura de GTK, con un valor de enum correspondiente y un <function>g_signal_new()</function> en el archivo .c.SimpleEjemplo simple de «Entry»Ejemplo simpleEjemplo de RecentChooserDialogEjemplo de texto simpleUso simpleWidgets libres como <classname>Gtk::Entry</classname> y <classname>Gtk::TextView</classname>proporcionan una función de copiar y pegar texto simple, pero tal vez necesite código especial para manejar sus propios formatos de datos. Por ejemplo, un programa de dibujo necesitaría código especial para permitir copiar y pegar dentro de una vista, o entre documentos.Dado que un <classname>Plug</classname> es sólo un tipo especial de la clase <classname>Gtk::Window</classname>, puede añadirle contenedores o widgets como si fuera cualquier otra ventana.Dado que la biblioteca de gráficos Cairo se escribió con soporte para múltiples objetivos de salida (el sistema de ventanas X, imágenes PNG, OpenGL, etc), hay una distinción entre las coordenadas espaciales del usuario y las del dispositivo. De manera predeterminada, estos dos sistemas de coordenadas están mapeados uno a uno, por lo que los valores enteros mapean aproximadamente a píxeles en la pantalla, pero esta configuración puede ajustarse si así se desea. A veces, puede ser útil escalar las coordenadas para que la anchura y la altura completos de la ventana vayan de 0 a 1 (el «cuadrado unitario»), o algún otro mapeo que funcione en su aplicación. Esto puede realizarse con la función <methodname>Cairo::Context::scale()</methodname>.Dado que esto es muy similar a los métodos mencionados anteriormente esta explicación es suficiente para entender lo que sucede. Sin embargo, aquí hay un pequeño ejemplo:Selección única o múltipleContenedor de un sólo elementoHasta ahora se la ha enseñado a realizar acciones en respuesta a pulsaciones de botones o eventos similares manejando señales. Esa es seguramente una buena manera de hacer las cosas, pero no es la única.Para que las aplicaciones puedan reaccionar a los cambios, por ejemplo, cuando un usuario mueve una barra de desplazamiento, <classname>Gtk::Adjustment</classname> tiene una señal <literal>value_changed</literal>.Entonces, usar el método <methodname>get_value()</methodname> para descubrir el valor nuevo.Para que la <classname>Entry</classname> pueda interactuar con la lista desplegable de opciones, debe especificar cuál de las columnas de su modelo es la columna de texto, con <methodname>set_text_column()</methodname>. Por ejemplo: <placeholder-1/>Por lo que debe evitar esta situación o usar <ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1ustring.html"><function>Glib::ustring::compose()</function></ulink> que soporta sintaxis como: <placeholder-1/>Entonces, por ejemplo, si tiene un widget <classname>Scale</classname>, y quiere cambiar la rotación de una imagen cuando su valor cambia, podría crear un manejador de señales de esta forma:«Sockets»Algunos widgets de <application>gtkmm</application> no tienen X-Windows asociadas; dibujan en las ventanas de sus padres. Es por esto que no pueden recibir eventos. Además, si tienen el tamaño incorrecto, no se recortan, por lo que puede aparecer sobrescritura errónea, etc. Para recibir eventos en uno de estos widgets, puede ponerlo dentro de un widget <classname>EventBox</classname> y después llamar a <methodname>Gtk::Widget::set_events()</methodname> en la «EventBox» antes de mostrarlo.Algunas API relacionadas con gtkmm utilizan contenedores de datos intermedios, como <classname>Glib::StringArrayHandle</classname>, en vez de un contenedor específico estándar de C++ como <classname>std::vector</classname> o <classname>std::list</classname>, a pesar de que <application>gtkmm</application> en sí mismo ahora sólo usa <classname>std::vector</classname> desde <application>gtkmm</application> 3.0.Algunos widgets no tienen una X-Window asociada, por lo que no reciben eventos de X. Esto significa que las señales descritas en la sección <link linkend="sec-xeventsignals">Señales de eventos de X</link> no se emitirán. Si quiere capturar eventos para estos widgets, puede usar un contenedor especial llamado <classname>Gtk::EventBox</classname>, que se describe en la sección <link linkend="sec-eventbox">EventBox</link>.Algunas macros adicionales hacen esto más fácil y consistente. Consulte los archivos .m4 de gtkmm como ejemplos. Por ejemplo: <placeholder-1/>Algunos objetos, como <classname>Gdk::Pixbuf</classname> y <classname>Pango::Font</classname>, se obtienen de un almacén compartido. Por lo tanto, no puede instanciar sus propias instancias. Estas clases típicamente heredan de <classname>Glib::Object</classname>. En lugar de requerirle referenciar y desreferenciar estos objetos, <application>gtkmm</application> usa el puntero inteligente <classname>Glib::RefPtr&lt;&gt;</classname>. Cairomm tiene su propio puntero inteligente, <classname>Cairo::RefPtr&lt;&gt;</classname>.Algunos de los tipos básicos que se usan en las API de C tienen alternativas mejores en C++. Por ejemplo, no hay necesidad de un tipo <type>gboolean</type> dado que C++ tiene el <type>bool</type>. La siguiente lista muestra algunos tipos comúnmente usados en API de C y en qué los puede convertir en una biblioteca envoltorio de C++Aún así, algunas reglas de seguridad de hilos sobre el uso de <classname>Glib::Dispatcher</classname> se aplican. Como se mencionó, un objeto <classname>Glib::Dispatcher</classname> debe construirse en el hilo receptor (aquel en cuyo bucle principal ejecutará sus «slot» conectados). Por defecto este es el hilo principal del programa, a pesar de que hay un constructor <classname>Glib::Dispatcher</classname> que toma el objeto <classname>Glib::MainContext</classname> de cualquier hilo que tiene un bucle principal. Solo el hilo receptor debe llamar a <methodname>connect()</methodname> en el objeto <classname>Glib::Dispatcher</classname>, o manipular cualquier objeto <classname>sigc::connection</classname> relacionado, a menos que se emplee sincronización adicional. Sin embargo, cualquier hilo de trabajo puede emitir con seguridad en el objeto <classname>Glib::Dispatcher</classname> sin bloquear una vez que el hilo receptor ha conectado los «slot», siempre que se construya antes de que el hilo de trabajo arranque (si se construye después, normalmente se requerirá sincronización adicional para asegurar la visibilidad).A veces, dos cadenas en inglés son idénticas pero tienen distintos significados en distintos contextos, por lo que probablemente no serían idénticas al traducirlas. Dado que las cadenas en inglés se usan como claves de búsqueda, esto causa problemas.OrdenarOrdenación al pulsar en columnasCódigo fuenteOrígenes y destinosEspecifica la carpeta de destino para las fuentes generadas, y el nombre del archivo .defs principal que <command>gmmproc</command> debe procesar.Especifica el nombre del parámetro «slot» del método, si tiene uno. Esto le permite a <command>gmmproc</command> generar código para copiar el «slot» y pasarle la copia a la función de C en su parámetro <literal>gpointer user_data</literal> final. La opción <literal>slot_callback</literal> también debe usarse para especificar el nombre de la función de devolución de llamada adhesiva que pasar a la función de C.Especificar los detalles del CellRendererSpinButtonEjecute el programa <filename>plug</filename> y envíelo a segundo plano (o simplemente use otra terminal).Las cadenas literales deben escribirse en el código fuente en inglés, pero rodeadas por una macro. La utilidad <application>gettext</application> (o intltool) puede entonces extraer las cadenas marcadas para traducción, y sustituir el texto traducido en tiempo de ejecución.Las cadenas literales deben introducirse en el código fuente en inglés, pero deben rodearse por una llamada a la función <function>gettext()</function>. Estas cadenas se extraerán para traducción y las traducciones podrán usarse en tiempo de ejecución en lugar de las cadenas originales en inglés.Herede los widgets para organizar mejor su código. Probablemente deba heredar al menos su <classname>Window</classname> principal. Entonces podrá hacer widgets hijos y manejadores de señales miembros de esa clase.La herencia no es siempre la mejor manera de realizar cosas. Sólo es útil cuando quiere que el widget maneje su propia señal por sí mismo. Si quiere que alguna otra clase maneje la señal entonces necesitará conectar un manejador separado. Esto es aún más cierto si quiere que varios objetos manejen la misma señal, o si quiere que un manejador de señales responda a la misma señal desde diferentes objetos.TablaTagTableEtiquetasEtiquetas y formateadoObjetivosLe dice a <command>gmmproc</command> que no le pase una copia del «slot» a la función de C, si el método tiene una. En su lugar, se pasa el «slot» en sí. El nombre del parámetro «slot» y la función de devolución de llamada adhesiva deben haberse especificado con las opciones <literal>slot_name</literal> y <literal>slot_callbback</literal> respectivamente.Le dice a <command>gmmproc</command> que añada código de inicialización para la interfaz.Le dice a <command>gmmproc</command> que añada algunos «typedefs», constructores, y métodos estándar a esta clase, como es apropiado cuando se envuelve un widget.Comprobar y añadir las traduccionesEl texto se dibuja a través de disposiciones de Pango. La manera más fácil de crear una <classname>Pango::Layout</classname> es usar <methodname>Gtk::Widget::create_pango_layout()</methodname>. Una vez creada, la disposición puede manipularse de varias maneras, incluyendo cambiar el texto, la tipografía, etc. Finalmente, la disposición puede mostrarse usando el método <methodname>Pango::Layout::show_in_cairo_context()</methodname>.El texto se renderiza usando Pango. El objeto <classname>Pango::Layout</classname> para la impresión debe crearse llamando al método <methodname>PrintContext::create_pango_layout()</methodname>. El objeto <classname>PrintContext</classname> también proporciona las medidas de la página, mediante <methodname>get_width()</methodname> y <methodname>get_height()</methodname>. El número de páginas puede establecerse con <methodname>PrintOperation::set_n_pages()</methodname>. Para renderizar el texto de Pango en <literal>on_draw_page</literal>, obtenga un <classname>Cairo::Context</classname> con <methodname>PrintContext::get_cairo_context()</methodname> y haga visibles las <classname>Pango::LayoutLine</classname> que aparecen dentro del número de página pedido.TextViewEso creará un archivo llamado <filename>programname.pot</filename>. Ahora, copie ese archivo a <filename>languagecode.po</filename>, como por ejemplo <filename>de.po</filename> o <filename>hu.po</filename>. También añada ese código de lenguaje a <literal>LINGUAS</literal>. El archivo <filename>.po</filename> contiene una cabecera y una lista de cadenas en inglés, con espacios para introducir las cadenas traducidas. Asegúrese de establecer la codificación del archivo <filename>.po</filename> (especificada en la cabecera, pero también en el contenido) a <literal>UTF-8</literal>.La señal «changed»La opción «imprimir a un archivo» está disponible en el diálogo de impresión, sin la necesidad de implementación adicional. Sin embargo, a veces es útil generar un archivo pdf directamente desde el código. Por ejemplo, <placeholder-1/>Los archivos .h y .cc se generarán desde los archivos .hg y .ccg procesándolos con <command>gmmproc</command> así, aunque esto sucede automáticamente cuando usa la estructura de construcción anteriormente mencionada: <placeholder-1/>Los archivos .hg y .ccgLos archivos de fuentes .hg y .ccg se parecen mucho a los archivos de fuentes .h y .cc de C++, pero contienen macros adicionales, como <function>_CLASS_GOBJECT()</function> y <function>_WRAP_METHOD()</function>, desde las que <command>gmmproc</command> genera código fuente de C++ apropiado, generalmente en la misma posición en la cabecera. Cualquier código fuente adicional de C++ se copiará tal cual en el archivo .h o .cc correspondiente.El paquete <application>GNU gettext</application> le permite marcar cadenas en el código fuente, extraer esas cadenas para su traducción, y usar las cadenas traducidas en su aplicación.El módulo de <application>gtkmm</application> se define en el conjunto de módulos <filename>gnome-suites-core-deps-3.x.modules</filename>, así que edite su archivo <filename>.jhbuildrc</filename> y establezca la configuración de su conjunto de módulos a la última versión, por ejemplo, así: <placeholder-1/>La clase <classname>AboutDialog</classname> ofrece una manera sencilla de mostrar información sobre el programa, como su logo, nombre, copyright, página web y licencia.El widget <classname>Alignment</classname> le permite poner un widget en una posición y tamaño relativos al tamaño del widget <classname>Alignment</classname> en sí. Por ejemplo, puede usarse para centrar un widget.El widget <classname>AspectFrame</classname> se ve como un widget <classname>Frame</classname>, pero fuerza la <emphasis>relación de aspecto</emphasis> (la razón entre la altura y el ancho) del widget hijo, añadiendo espacio adicional de ser necesario. Por ejemplo, esto le permitiría mostrar una fotografía sin permitirle al usuario distorsionarla horizontal o verticalmente cuando la redimensione.El <classname>ColorChooserDialog</classname> le permite al usuario elegir un color. El <classname>ColorButton</classname> abre un diálogo de selección de color cuando se pulsa.Los widgets <classname>ComboBox</classname> ofrecen una lista (o árbol) de opciones en un menú desplegable. Si es apropiado, puede mostrar información adicional acerca de cada elemento, como texto, una imagen, una casilla de verificación, o una barra de progreso. Generalmente, el widget <classname>ComboBox</classname> sólo le permite elegir al usuario entre las opciones disponibles, pero opcionalmente puede tener un <classname>Entry</classname>, permitiéndole al usuario introducir texto arbitrario si ninguna de las opciones disponibles es apropiada.El widget <classname>DrawingArea</classname> es una ventana vacía que le da la libertad de crear cualquier gráfico que desee. Junto con esa libertad viene la responsabilidad de manejar las señales de dibujo en el widget. Cuando un widget se muestra por primera vez, o cuando se cubre y descubre, debe redibujarse a sí mismo. La mayoría de los widgets tiene código para hacer esto, pero el área de dibujo no, permitiéndole escribir su propio manejador de señales de dibujo para determinar cómo se dibujarán los contenidos del widget. La mayor parte de las veces, esto se hace sobrecargando la función miembro virtual <methodname>on_draw()</methodname>.El <classname>EntryCompletion</classname> puede usar un <classname>TreeModel</classname> que contenga las entradas posibles, especificadas por <methodname>set_model()</methodname>. Luego llame a <methodname>set_text_column()</methodname> para especificar cuál de las columnas de su modelo debe usarse para las posibles entradas de texto.El <classname>FileChooserDialog</classname> es adecuado para usarse con elementos «abrir» o «guardar» en el menú.El <classname>FontChooserDialog</classname> le permite al usuario elegir una tipografía. El <classname>FontButton</classname> abre un diálogo de selección de tipografía cuando se pulsa.El <classname>Gdk::Pixbuf</classname> puede procesarse estableciéndolo como el patrón fuente del contexto de Cairo con <methodname>Gdk::Cairo::set_source_pixbuf()</methodname>. Después, dibuje la imagen con <methodname>Cairo::Context::paint()</methodname> (para dibujar la imagen entera), o <methodname>Cairo::Context::rectangle()</methodname> y <methodname>Cairo::Context::fill()</methodname> (para rellenar el rectángulo especificado). <methodname>set_source_pixbuf()</methodname> no es un miembro de <classname>Cairo::Context</classname>. Toma un <classname>Cairo::Context</classname> como primer parámetro.El widget <classname>Gtk::Button</classname> tiene las siguientes señales, pero la mayor parte del tiempo sólo manejara la señal <literal>clicked</literal>:El widget <classname>Gtk::TreeView</classname> puede contener listas o árboles de datos, en columnas.El <classname>ListStore</classname> contiene filas simples de datos, y ninguna fila tiene hijos.La clase <classname>PrintOperation</classname> tiene un método llamado <methodname>set_default_page_setup()</methodname> que selecciona el tamaño de papel, orientación y márgenes predeterminados. Para mostrar un diálogo de configuración de página desde su aplicación, use el método <methodname>Gtk::run_page_setup_dialog()</methodname>, que devuelve un objeto <classname>Gtk::PageSetup()</classname> con la configuración elegida. Use este objeto para actualizar una <classname>PrintOperation</classname> y acceder a <classname>Gtk::PaperSize</classname>, <literal>Gtk::PageOrientation</literal> y los márgenes específicos de la impresora.El <classname>SpinButton</classname> puede crear un <classname>Adjustment</classname> predeterminado, al que puede acceder mediante el método <methodname>get_adjustment()</methodname>, o puede especificar un <classname>Adjustment</classname> existente en el constructor.La clase <classname>Tag</classname> tiene muchas otras propiedades.El <classname>TextView</classname> crea su propio <classname>TextBuffer</classname> predeterminado, al que puede acceder mediante el método <methodname>get_buffer()</methodname>.El widget <classname>TextView</classname> puede usarse para mostrar y editar grandes cantidades de texto formateado. Al igual que el <classname>TreeView</classname>, tiene un diseño modelo/vista. En este caso, el <classname>TextBuffer</classname> es el modelo.Los elementos del <classname>ToolPalette</classname> pueden arrastrarse o simplemente activarse. Por ejemplo, el usuario tal vez arrastre objetos a un lienzo para crear elementos nuevos allí. O bien, el usuario podría pulsar sobre un elemento para activar un determinado tamaño de pincel en una aplicación de dibujo.La clase <classname>TreeModelColumnRecord</classname> se usa para rastrear a las columnas y sus tipos de datos. Añádale instancias <classname>TreeModelColumn</classname> al <classname>ColumnRecord</classname> y luego use esas <classname>TreeModelColumn</classname> cuando establezca u obtenga los datos en las filas del modelo. Probablemente encuentre conveniente derivar un <classname>TreeModelColumnRecord</classname> que tenga a sus instancias <classname>TreeModelColumn</classname> como datos miembro.El <classname>TreeStore</classname> contiene filas de datos, y cada fila puede tener filas hijas.El <classname>TreeView</classname> ya le permite mostrar al mismo <classname>TreeModel</classname> en dos widgets <classname>TreeView</classname>. Si necesita que uno de estos «TreeView» ordene el modelo de manera diferente al otro, entonces use un <classname>TreeModelSort</classname> en lugar de solo, por ejemplo, <methodname>Gtk::TreeViewModel::set_sort_column()</methodname>. <classname>TreeModelSort</classname> es un modelo que contiene a otro modelo, presentando una versión ordenada de ese modelo. Por ejemplo, puede añadir una versión ordenada de un modelo a un <classname>TreeView</classname> así:La clase <classname>Widget</classname> tiene algunas señales especiales que corresponden a los eventos de X-Window subyacentes. Estas tienen el sufijo <literal>_event</literal>; por ejemplo, <methodname>Widget::signal_button_press_event()</methodname>.La <emphasis>política de actualización</emphasis> de un widget <classname>Range</classname> define en qué puntos durante la interacción del usuario cambiará el campo <literal>value</literal> de su <classname>Gtk::Adjustment</classname> y se emitirá la señal <literal>value_changed</literal>. Las políticas de actualización, que se establecen con el método <methodname>set_update_policy()</methodname>, son: <placeholder-1/>Los archivos <filename>.defs</filename> son archivos de texto, en formato «lisp», que describen la API de la biblioteca de C, incluyendo sus <placeholder-1/>El script <filename>configure</filename> hará comprobaciones para asegurarse de que todas las dependencias necesarias ya están instaladas. Si le falta alguna dependencia, terminará y mostrará un error.El bloque <function>AC_CONFIG_FILES()</function> debe mencionar a los nombres de carpetas correctos, como se describió anteriormente.La línea <function>AC_CONFIG_SRCDIR()</function> debe mencionar un archivo en el árbol de fuentes. Se puede editar esto más tarde si todavía no se saben los nombres de ninguno de los archivos que se crearán.La línea <function>AC_SUBST([SOMETHINGMM_MODULES], ['...'])</function> tal vez necesite modificarse para verificar las dependencias correctas.Las macros <function>_CTOR_DEFAULT()</function> y <function>_WRAP_CTOR()</function> añaden constructores, envolviendo las funciones de C <function>*_new()</function> especificadas. Estas macros asumen que el objeto de C tiene propiedades con los mismos nombres que los parámetros de función, como es usual, para que pueda proporcionar los parámetros directamente a una llamada de <function>g_object_new()</function>. Estos constructores nunca llaman realmente a funciones de C <function>*_new()</function>, porque gtkmm debe en realidad instanciar «GTypes» derivados, y las funciones <function>*_new()</function> de C sólo están pensadas como funciones cómodas para programadores de C.La API <link linkend="chapter-draganddrop">Arrastrar y soltar</link> usa el mismo mecanismo. Probablemente deba usar los mismos objetivos de datos y formatos para las operaciones de arrastrar y soltar así como para las de portapapeles.El <literal>const ... &amp;</literal> que los rodea está sólo por eficiencia, como usar <literal>const std::string&amp;</literal> en lugar de <classname>std::string</classname> como método de parámetro para evitar una copia innecesaria.El ejemplo <literal>ideal</literal> a continuación puede proporcionar más de un objetivo para el portapapeles.El método <methodname>PrintOperation::run()</methodname> comienza el ciclo de impresión, durante el que se emiten varias señales: <placeholder-1/>Los métodos virtuales <methodname>get_request_mode_vfunc()</methodname>, <methodname>get_preferred_width_vfunc()</methodname>, <methodname>get_preferred_height_vfunc()</methodname>, <methodname>get_preferred_width_for_height_vfunc()</methodname>, <methodname>get_preferred_height_for_width_vfunc()</methodname>, y <methodname>on_size_allocate()</methodname> controlan la distribución de los widgets hijos. Por ejemplo, si su contenedor tiene 2 widgets hijos, con uno debajo del otro, su <methodname>get_request_mode_vfunc()</methodname> puede pedir una distribución de altura por anchura. Después su <methodname>get_preferred_width_vfunc()</methodname> puede reportar el máximo de las anchuras de los widgets hijos, y <methodname>get_preferred_height_for_width_vfunc()</methodname> puede reportar la suma de sus anchuras. Si quiere espacios entre los widgets hijos, entonces añádaselos a la altura y a la anchura también. El contenedor de su widget usará este resultado para asegurarse de que obtenga espacio suficiente, y no menos. Examinando al padre de cada widget, y a su padre, esta lógica eventualmente decidirá el tamaño de la ventana de nivel superior.Los métodos <methodname>pack_start()</methodname> y <methodname>pack_end()</methodname> ponen widgets dentro de estos contenedores. El método <methodname>pack_start()</methodname> empezará arriba, y seguirá hacia abajo en una <classname>Box</classname> de orientación vertical, o empaquetará de izquierda a derecha en una <classname>Box</classname> de orientación horizontal. <methodname>pack_end()</methodname> hará lo contrario, empaquetando de abajo hacia arriba o de derecha a izquierda. Usar estos métodos le permite justificar a derecha o izquierda a sus widgets. Se usará <methodname>pack_start()</methodname> en la mayoría de los ejemplos.El método <methodname>run()</methodname> devuelve un <literal>int</literal>. Este podría ser el valor del <literal>Gtk::ResponseType</literal> si el usuario cerró el diálogo pulsando un botón estándar, o podría ser la respuesta personalizada que ha especificado cuando usó <methodname>add_button()</methodname>.El método <methodname>spin()</methodname> «gira» el <classname>SpinButton</classname>, como si se hubiera presionado una de sus flechas. Debe especificar un <classname>Gtk::SpinType</classname> para especificar la dirección de su posición nueva.El argumento <parameter>options</parameter> puede tomar una de estas tres opciones: <placeholder-1/>El argumento <parameter>padding</parameter> especifica el ancho de un área adicional en el borde para dejar alrededor del widget empaquetado.El búferLa función de C (por ejemplo, <function>get_request_mode</function>) se describe en mayor detalle en el archivo <filename>*_vfuncs.defs</filename>, y los archivos <filename>convert*.m4</filename> contienen las conversiones necesarias del tipo de parámetro de C++ al tipo de parámetro de C.La función de C (por ejemplo, <function>gtk_entry_set_text</function>) se describe en mayor detalle en el archivo .defs, y los archivos <filename>convert*.m4</filename> contienen la conversión necesaria del tipo de parámetro de C++ al tipo de C. Esta macro también genera comentarios de documentación de Doxygen basados en los archivos <filename>*_docs.xml</filename> y <filename>*_docs_override.xml</filename>.El modelo de dibujo de CairoEl sistema de coordenadas de Cairo, en el manejador <literal>draw_page</literal>, rota automáticamente a la orientación de la página actual. Normalmente está dentro de los márgenes de la impresora, pero puede cambiar esto mediante el método <methodname>PrintOperation::set_use_full_page()</methodname>. La unidad de medida predeterminada es el píxel del dispositivo. Para seleccionar otras unidades, use el método <methodname>PrintOperation::set_unit()</methodname>.El portapapelesEl widget de área de dibujoEl modeloEl puntero inteligente RefPtrLa selecciónEl widget TreeViewLa distribución de la IU para un menú emergente debe usar el nodo <literal>popup</literal>. Por ejemplo:La vistaLa vista es el widget en sí (<classname>Gtk::TreeView</classname>) que muestra los datos del modelo (<classname>Gtk::TreeModel</classname>) y le permite al usuario interactuar con él. La vista puede mostrar todas las columnas del modelo, o sólo algunas, y puede mostrarlas de varias maneras.Los widgets ajustables pueden dividirse en aquellos que usan y requieren unidades específicas para estos valores, y aquellos que los tratan como números arbitrarios.Los argumentos de <methodname>Action::create()</methodname> especifican el nombre de la acción y cómo aparecerá en los menús y las barras de herramientas.El concepto básico de dibujar con Cairo implica definir caminos «invisibles» y luego tacharlos o rellenarlos para hacerlos visibles.La estructura de construcciónEl elemento elegidoLas macros de clases declaran la clase en sí y su relación con el tipo de C subyacente. Generan algunos constructores internos, el miembro <varname>gobject_</varname>, «typedefs», los <function>gobj()</function> de acceso, registro de tipos, y el método <function>Glib::wrap()</function>, entre otras cosas.El retorno de llamada «clear» le permite liberar la memoria que sus datos almacenados usan cuando el portapapeles reemplaza sus datos con otra cosa.Las opciones de línea de comandos pasadas al preprocesador de C.Las opciones de línea de comandos pasadas al compilador de C++La comunicación entre un <classname>Socket</classname> y un <classname>Plug</classname> sigue el protocolo «XEmbed». Este protocolo, que también se ha implementado en otros kits de herramientas (por ejemplo, «Qt»), permite el mismo nivel de integración cuando se incrusta un widget Qt en uno GTK+ o viceversa.El compilador le hará saber si usa un tipo inapropiado. Por ejemplo, esto generaría un error de compilación:Las variantes de «connect*_once()», <methodname>Glib::SignalIdle::connect_once()</methodname>, <methodname>Glib::SignalTimeout::connect_once()</methodname>, <methodname>Glib::SignalTimeout::connect_seconds_once()</methodname>, son seguras para hilos para cualquier caso en el que el «slot» no lo cree una llamada a <methodname>sigc::mem_fun()</methodname> que represente a un método de una clase derivada de <methodname>sigc::trackable</methodname>. Esto es similar a <methodname>Glib::Threads::Thread::create()</methodname> como se menciona en el punto 4.Las limitacionesEl constructor de <classname>ExampleWindow</classname> crea el menú usando <classname>UIManager</classname> (consulte la <xref linkend="chapter-menus-and-toolbars"/> para obtener más información). Luego, añade el menú y la barra de herramientas a la ventana.El constructor de <classname>Gtk::EventBox</classname> es:El estado actual de un <classname>Cairo::Context</classname> puede guardarse en una pila interna de estados guardados y restaurarse más tarde como estaba cuando lo guardó. Para hacer esto, use los métodos <methodname>save()</methodname> y <methodname>restore()</methodname>. Esto puede ser útil si necesita cambiar la anchura y color de línea temporalmente (o cualquier otra configuración de gráficos) para dibujar algo y luego volver a la configuración anterior. En esta situación, puede llamar a <methodname>Cairo::Context::save()</methodname>, cambiar las opciones gráficas, dibujar las líneas, y luego llamar a <methodname>Cairo::Context::restore()</methodname> para restaurar el estado de gráficos original. Múltiples llamadas a <methodname>save()</methodname> y <methodname>restore()</methodname> pueden anidarse; cada llamada a <methodname>restore()</methodname> restaura el estado de su par <methodname>save()</methodname> correspondiente. <placeholder-1/>Las señales de arrastrar y soltar proporcionan un DragContext, que contiene información acerca de la esta operación y puede usarse para influir en el proceso. Por ejemplo, puede descubrir el widget de origen, o cambiar el icono de arrastrar y soltar, usando el método <methodname>set_icon()</methodname>. Aún más importante, debe llamar al método <methodname>drag_finish()</methodname> desde su manejador de señal <literal>drag_data_received</literal> para indicar si la operación tuvo éxito.La entradaEl evento se entrega primero al widget en el que ocurrió. Si todos los manejadores de señales de ese widget devuelven <literal>false</literal> (indicando que el evento no se ha manejado), entonces la señal se propagará al widget padre y se emitirá allí. Esto continúa hasta el widget de nivel superior si ninguno maneja el evento.El evento se propagará hasta que alcance el widget de mayor nivel, o hasta que detenga la propagación devolviendo <literal>true</literal> desde un manejador de eventos.El ejemplo en examples/book/printing/advanced demuestra esto.El «typedef» adicional le permite usar la estructura en una cabecera sin incluir su definición completa, simplemente predeclarándola repitiendo ese «typedef». Esto significa que no tiene que incluir la cabecera de la biblioteca de C en su cabecera de C++, por lo tanto la dejará fuera de su API pública. <command>gmmproc</command> asume que se usó esta técnica, por lo que verá errores de compilación si ese no es el caso.Los 6 primeros métodos en la tabla anterior también se reemplazan en los contenedores personalizados. Se describen brevemente en la sección <link linkend="sec-custom-containers">Contenedores personalizados</link>.El primer argumento es un <classname>slot</classname> al que quiere que se llame cuando pase el período de espera. El segundo argumento es el número de milisegundos entre llamadas a ese método. Recibirá un objeto <classname>sigc::connection</classname> que podrá usar para desactivar la conexión utilizando su método <methodname>disconnect()</methodname>:El primer argumento es el widget que está empaquetando. En el ejemplo estos son todos los <classname>Button</classname>.La primera llamada a <methodname>connect()</methodname> es igual a la que vio la última vez; no hay nada nuevo aquí.La primera línea de la salida es de <filename>plug</filename>, después de que se le ha notificado que se empotró en un <classname>Socket</classname>. La segunda línea la emite <filename>socket</filename> en respuesta a su señal <methodname>plug_added</methodname>. Si todo se realizó como se describió anteriormente, la ventana <filename>socket</filename> debería verse más o menos así:El siguiente ejemplo demuestra ambos usos de una <classname>EventBox</classname>: se crea una etiqueta que se adjunta a un pequeño cuadro, configurada de manera que una pulsación del ratón en ella hace que el programa termine. Redimensionar la ventana revelará partes variables de la etiqueta.El siguiente ejemplo demuestra cómo imprimir entrada desde una interfaz de usuario. Muestra cómo implementar <literal>on_begin_print</literal> y <literal>on_draw_page</literal>, como también cómo rastrear el estado de la impresión y actualizar sus opciones.El siguiente ejemplo muestra el uso de <classname>RadioButton</classname>:El siguiente programa de ejemplo requiere una opción de línea de comandos. El código fuente muestra dos maneras de manejarla, en combinación con <classname>Gtk::Application</classname>.El siguiente ejemplo muestra cómo crear un contexto Cairo con un color de frente rojo y un ancho de 2. Cualquier función de dibujo que use este contexto usará esta configuraciónEl siguiente es un ejemplo simple del uso de «sockets» y «plugs». El método de comunicación entre los procesos se mantiene simple deliberadamente: el <classname>Plug</classname> escribe su ID en un archivo de texto llamado <filename>plug.id</filename> y el proceso con el «socket» lee el ID de este archivo. En un programa real, probablemente quiera usar un método más sofisticado de comunicación entre procesos.El siguiente programa usa un <classname>Gtk::AspectFrame</classname> para presentar un área de dibujo cuya relación de aspecto siempre es 2:1, sin importar cómo el usuario redimensiona la ventana superior.La función <methodname>Cairo::Context::arc_negative()</methodname> es exactamente la misma que <methodname>Cairo::Context::arc()</methodname>, pero los ángulos van en la dirección opuesta.Las funciones <methodname>move_item()</methodname>, <methodname>remove_item()</methodname> y <methodname>purge_items()</methodname> no tienen efecto en los archivos en sí a los que se refieren los URI, sólo modifican la lista de archivos recientes.El grupo que trata los valores como números arbitrarios incluye los widgets <classname>Range</classname> (<classname>Scrollbar</classname> y <classname>Scale</classname>), el widget <classname>ScaleButton</classname> y el widget <classname>SpinButton</classname>. Típicamente, el usuario «ajusta» directamente a estos widgets mediante el teclado o el ratón. Tratarán a los valores <parameter>lower</parameter> y <parameter>upper</parameter> de un ajuste como un rango dentro del cual el usuario podrá manipular el <parameter>value</parameter> del ajuste. De manera predeterminada, sólo modificarán el <parameter>value</parameter> de un ajuste.<filename>generate_wrap_init.pl</filename> genera la implementación del método <function>wrap_init()</function> en <filename>wrap_init.cc</filename>, pero la declaración en <filename>wrap_init.h</filename> se programa a mano, por lo que necesitará ajustar <filename>wrap_init.h</filename> de manera tal que la función <function>wrap_init()</function> aparezca en el espacio de nombres de C++ correcto.El texto de la etiqueta se puede justificar usando el método <methodname>set_justify()</methodname>. El widget también es capaz de ajustar el texto, lo que se puede activar con <methodname>set_line_wrap()</methodname>.La última línea muestra la ventana y entra al bucle principal de <application>gtkmm</application>, que terminará cuando la ventana se cierre. Su función <function>main()</function> entonces retornará con un éxito apropiado o un código de error.El estilo de unión de línea se establece usando la función <methodname>Cairo::Context::set_line_join()</methodname>.Un <classname>TreeModel</classname> proporciona la lista, y las columnas de este modelo se añaden a la vista del «ComboBox» con el método <methodname>ComboBox::pack_start()</methodname>. Esto proporciona flexibilidad y seguridad de tipos en tiempo de compilación, pero la clase <classname>ComboBoxText</classname> proporciona una especialización más simple basada en texto en caso de que no se requiera la flexibilidad.Las macros se explican en mayor detalle en las secciones siguientes.Las macros en este ejemplo hacen lo siguiente: <placeholder-1/>Las macros que usa en los archivos .hg y .ccg a menudo necesitan saber cómo convertir un tipo de C++ a un tipo de C, o viceversa. gmmproc toma esta información desde un archivo .m4 en su carpeta <literal>tools/m4/</literal>. Esto le permite llamar a una función de C en la implementación de su método de C++, pasándole los parámetros apropiados a esa función de C. Por ejemplo, esto le dice a gmmproc cómo convertir un puntero de GtkTreeView a un puntero de Gtk::TreView: <placeholder-1/>La principal actividad en el proceso de internacionalización es encontrar las cadenas vistas por los usuarios y marcarlas para traducir. No necesita hacerlo todo de una vez: si crea la infraestructura del proyecto necesaria correctamente, entonces su aplicación funcionará normalmente sin importar cuántas cadenas ha cubierto.La edad máxima de los elementos de la lista de archivos usados recientemente puede establecerse con <methodname>Gtk::Settings::property_gtk_recent_files_max_age()</methodname>. El valor predeterminado es 30 días.El modeloEl modelo de una «ComboBox» puede definirse y llenarse exactamente como un <classname>TreeView</classname>. Por ejemplo, puede derivar una clase «ComboBox» con una columna de números enteros y otra de texto, así:El nombre de la biblioteca, por ejemplo libsomethingmm.Los nombres de los paquetes de <application>gtkmm</application> varían de distribución en distribución (por ejemplo, <application>libgtkmm-3.0-dev</application> en Debian y en Ubuntu o <application>gtkmm30-devel</application> en Red Hat y Fedora), por lo que se recomienda consultar el nombre del paquete correcto en el gestor de paquetes de su distribución para instalarlo como lo haría con cualquier otro paquete.El diálogo de impresión nativo de GTK+ tiene un botón de previsualización, pero también puede comenzar una previsualización directamente desde una aplicación: <placeholder-1/>La siguiente es más interesante. <function>sigc::mem_fun()</function> se llama con dos argumentos. El primero es <parameter>some_object</parameter>, que es el objeto al que su nuevo «slot» apuntará. El segundo argumento es un puntero a uno de sus métodos. Esta versión particular de <function>sigc::mem_fun()</function> crea un «slot» que, cuando se «llame», llamará al método al que apunta del objeto especificado, en este caso, <methodname>some_object.on_button_clicked()</methodname>.La siguiente línea: <placeholder-1/> crea un objeto <classname>Gtk::Application</classname>, almacenado en un puntero inteligente <classname>RefPtr</classname>. Esto es necesario en todas las aplicaciones <application>gtkmm</application>. El método «create()» de este objeto inicializa <application>gtkmm</application> y verifica los argumentos pasados a su aplicación en la línea de comandos, buscando opciones estándar tales como <literal>--display</literal>. Toma estos argumentos de la lista, dejándole cualquier cosa que no reconozca para que su aplicación la procese o la ignore. Esto asegura que todas las aplicaciones <application>gtkmm</application> acepten el mismo conjunto de argumentos estándar.Las dos siguientes líneas de código crean una ventana y establecen su tamaño (inicial) predeterminado:La cantidad de lugares decimales se puede alterar usando el método <methodname>set_digits()</methodname>.La única diferencia entre este ejemplo y el de la línea recta está en la función <methodname>on_draw()</methodname>, pero hay unos conceptos y funciones nuevas presentadas aquí, así que se examinarán brevemente.La orientación de una <classname>Gtk::Scrollbar</classname> puede ser horizontal o vertical.El otro grupo incluye al widget <classname>Viewport</classname> y al widget <classname>ScrolledWindow</classname>. Todos estos widgets usan valores de píxel para sus ajustes. Típicamente, estos también se ajustan indirectamente usando barras de desplazamiento. A pesar de que todos los widgets que usan ajustes pueden crear los suyos o usar los que se les proporcionan, generalmente querrá dejarle a esta categoría particular de widgets crear sus propios ajustes.Los nombres de los paquetes no cambiarán cuando se libere la nueva API/ABI compatible con versiones de <application>gtkmm</application>. De lo contrario, no sería una API/ABI compatible. Así que no se sorprenda, por ejemplo, de encontrar <application>gtkmm</application> 3.8 suministrado por el paquete <application>libgtkmm-3.0-dev</application> de Debian.La principal desventaja de usar widgets de alcance de clase es revelar la implementación de la clase en lugar de la interfaz en su cabecera.El objeto primario es <classname>Gtk::PrintOperation</classname>, reservado por cada operación de impresión. Para manejar el dibujo de una página, conecte sus señales, o herede de él y sobrecargue los manejadores de señales virtuales predeterminados. <classname>PrintOperation</classname> maneja automáticamente todas las opciones que afectan al bucle de impresión.El proceso de escribir código fuente que se pueda traducir se llama <literal>internacionalización</literal>, a menudo abreviado como <literal>i18n</literal>. El proceso de <literal>localización</literal>, a veces abreviado <literal>l10n</literal>, proporciona el texto traducido a otros lenguajes, basado en ese código fuente.La barra de progreso también puede mostrar una cadena de texto configurable en su canal, usando el método <methodname>set_text()</methodname>.El propósito de este ejemplo es mostrar los pasos que el evento sigue cuando se emite.El valor de retorno es una <classname>sigc::connection</classname> que puede usarse para detener la monitorización del descriptor de archivos usando su método <methodname>disconnect()</methodname>. El manejador de señales <parameter>slot</parameter> debe declararse de la siguiente manera:Las reglasLos mismos principios se aplican a las señales que tienen más argumentos. Aquí hay una con tres (tomada de <filename>&lt;gtkmm/textbuffer.h&gt;</filename>):La segunda manera de establecer botones de radio es hacer primero un grupo y luego añadirle los botones a él. Aquí hay un ejemplo:La sección para dibujar un arco presenta una nueva función, <methodname>close_path()</methodname>. Esta función, en efecto, dibujará una línea recta desde el punto actual de vuelta al primer punto en el camino. Sin embargo, hay una diferencia significativa entre llamar a <methodname>close_path()</methodname> y dibujar una línea manualmente al punto de inicio. Si usa <methodname>close_path()</methodname>, las líneas se juntarán suavemente. Si usa <methodname>line_to()</methodname> en su lugar, las líneas terminarán en el mismo lugar, pero Cairo no las juntará de manera especial.Las filas seleccionadasEl manejador de señales es <methodname>on_button_clicked()</methodname>.Los contenedores de un sólo elemento derivan de <classname>Gtk::Bin</classname>, que proporciona los métodos <methodname>add()</methodname> y <methodname>remove()</methodname> para el widget hijo. Tenga en cuenta que <classname>Gtk::Button</classname> y <classname>Gtk::Window</classname> son, técnicamente, contenedores de un sólo elemento, pero ya se ha hablado de ellos anteriormente.Los «slots» conectados a objetos <classname>sigc::signal</classname> se ejecutan en el hilo que llama a <methodname>emit()</methodname> u <methodname>operator()()</methodname> en la señal. <classname>Glib::Dispatcher</classname> no se comporta de esa manera: en su lugar, sus «slots» conectados se ejecutan en el hilo en el que el objeto <classname>Glib::Dispatcher</classname> se construyó (que debe tener un bucle principal de glib). Si un objeto <classname>Glib::Dispatcher</classname> se construye en el hilo principal de la IGU (que por ende será el hilo receptor), cualquier hilo de trabajo puede emitir sobre él y sus «slot» conectados podrán ejecutar funciones de <application>gtkmm</application> con seguridad.El widget origen emitirá estas señales, en este orden: <placeholder-1/>Los modelos de árbol estándar (<classname>TreeStore</classname> y <classname>ListStore</classname>) derivan de <classname>TreeSortable</classname>, por lo que ofrecen funciones de ordenación. Por ejemplo, llame a <methodname>set_sort_column()</methodname> para ordenar el modelo por la columna especificada. O, proporcione una función de retorno de llamada a <methodname>set_sort_func()</methodname> para implementar un algoritmo de ordenación más complejo.La columna de textoEl truco está en posicionarse en la mitad del píxel en el que quiere que se dibuje la línea, garantizando así que obtendrá los resultados deseados. Consulte las <ulink url="http://cairographics.org/FAQ/#sharp_lines">preguntas más frecuentes de Cairo</ulink>.El uso de la palabra reservada <literal>const</literal> en C++ no siempre es claro. Puede no darse cuenta de que <type>const Algo*</type> declara un puntero a un <type>const Algo</type>. El puntero puede cambiarse, pero no el <type>Algo</type> al que apunta.El valor puede tener un número ajustable de decimales, y el tamaño del paso es configurable. Los <classname>SpinButton</classname> también tienen una característica de «auto-repetición»: mantener pulsada una de las flechas puede, opcionalmente, causar que el valor cambie más rápidamente cuanto más tiempo se mantenga pulsada la flecha.El valor mostrado en un widget de escala se redondea a un dígito decimal de manera predeterminada, como es el campo <literal>value</literal> en su <classname>Gtk::Adjustment</classname>. Puede cambiar esto con el método <methodname>set_digits()</methodname>.El método virtual <methodname>on_draw()</methodname> proporciona un contexto Cairo que deberá usar para dibujar en el widget <classname>Gtk::DrawingArea</classname>. No es necesario guardar y restaurar este contexto Cairo en <methodname>on_draw()</methodname>.Consiste en que contacte a la lista de correo gnome-i18n para descubrir cómo los traductores pueden acceder a su subcarpeta <filename>po/</filename>, y añadir su proyecto a la <ulink url="http://l10n.gnome.org/module/">lista de módulos para traducir</ulink>.La manera en la que los <classname>Sockets</classname> y los <classname>Plugs</classname> trabajan juntos es a través de sus ID de ventana. Tanto un <classname>Socket</classname> como un <classname>Plug</classname> tienen ID que pueden obtenerse con sus funciones miembro <methodname>get_id()</methodname>. El uso de estos ID se explicará a continuación en la <xref linkend="sec-connecting-plugs-sockets"/>.Los widgets no se reordenar cuando la ventana se redimensiona. Algunos se esconden cuando las ventanas se hacen más pequeñas, y aparece un montón de espacio sin utilizar cuando la ventana se agranda.El ancho de la etiqueta se ajusta automáticamente. Puede producir etiquetas con varias líneas poniendo saltos de línea («\n») en la cadena de la etiqueta.The window ID is: 69206019Después edite el archivo <filename>.cc</filename> para especificar los tipos correctos. Por ejemplo, su función <function>main()</function> podría verse así: <placeholder-1/>Entonces, ejecute el programa <filename>socket</filename>:Después asegúrese de actualizar el archivo <filename>POTFILES.in</filename> en la subcarpeta <filename>po/</filename> (<command>intltool -update -M</command> le puede ayudar con esto) para que los traductores siempre accedan a archivos <filename>myprogram.pot</filename> actualizados, y simplemente congelen las cadenas por lo menos un par de días antes de que libere una versión nueva, anunciándolo en gnome-i18n. Dependiendo del número de cadenas que su programa contenga y cómo de popular sea, los traductores empezarán a generar archivos <filename>languagename.po</filename>.Luego, para añadir un widget en esa posición, use <methodname>Gtk::TextView::add_child_at_anchor()</methodname>:Luego, puede definir la distribución visible real de los menús y las barras de herramientas, y añadírsela al <classname>UIManager</classname>. Esta «cadena de IU» usa un formato XML, en el que debe mencionar los nombre de las acciones que ya ha creado. Por ejemplo:Hay un par de cosas que debe tener en cuenta acerca de este código de ejemplo. Nuevamente, la única diferencia real entre este ejemplo y los anteriores es la función <methodname>on_draw()</methodname>, por lo que nos limitaremos a trabajar esa función. Además, la primera parte de la función es casi idéntica a la de los ejemplos previos, por lo que se omitirá ese fragmento.Hay algunos errores comunes que eventualmente descubriría por sí mismo. Pero esta sección le ayudará a evitarlos.Hay varias variables del estado de gráficos que pueden establecerse para un contexto Cairo. Los atributos de contexto más comunes son color (usando <methodname>set_source_rgb()</methodname> o <methodname>set_source_rgba()</methodname> para colores traslúcidos), anchura de línea (usando <methodname>set_line_width()</methodname>), patrón de línea de puntos (usando <methodname>set_dash</methodname>), estilo de terminación de línea (usando <methodname>set_line_cap()</methodname>), estilo de unión de línea (usando <methodname>set_line_join()</methodname>), y estilos de fuente (usando <methodname>set_font_size()</methodname>, <methodname>set_font_face()</methodname> y otros). Hay muchas otras opciones también, como matrices de transformación, reglas de rellenado, realización de «antialiasing», y otros. Para obtener más información, consulte la documentación de la API de <ulink url="http://www.cairographics.org/cairomm/">cairomm</ulink>.Básicamente, hay cinco estilos diferentes, como se muestra en esta imagen.Además, hay otras cosas que puede personalizar, incluyendo la creación de líneas punteadas y otras cosas. Para obtener más información, consulte la documentación de la API de Cairo.Hay varias clases <classname>Dialog</classname> derivadas que podría encontrar útiles. <classname>Gtk::MessageDialog</classname> se usa para las notificaciones más simples. Pero en otras ocasiones, tal vez necesite derivar su propia clase de diálogo para proporcionar una funcionalidad más compleja.Hay muchas opciones que determinan cómo se empaquetan los widgets, y esto puede resultar confuso al principio. Si tiene dificultades, entonces a veces es una buena idea jugar con el diseñador de IGU <application>glade</application> para ver qué es posible. Incluso, tal vez decida usar la API de <application>Gtk::Builder</application> para cargar su IGU en tiempo de ejecución.Hay muchos más contenedores, de los que también se hablará.Hay algunos argumentos opcionales adicionales: <placeholder-1/>Hay API específicas para los menús y las barras de herramientas, pero usualmente debe tratarlas juntas, usando el <classname>UIManager</classname> para definir <classname>Action</classname> que puede ordenar en menús y barras de herramientas. De esta forma, puede manejar la activación de la acción en lugar de responder a los elementos del menú y las barras de herramientas separadamente. Y puede activar o desactivar tanto el elemento del menú como el de la barra de herramientas a través de la acción.Existen dos estrategias básicas que pueden usarse: <placeholder-1/>Hay dos clases <classname>Mark</classname> incorporadas: <literal>insert</literal> y <literal>select_bound</literal>, a las que puede acceder con los métodos <methodname>get_insert()</methodname> and <methodname>get_selection_bound()</methodname> de <classname>TextBuffer</classname>.Hay dos maneras de crear un botón. Puede especificar una etiqueta en el constructor de <classname>Gtk::Button</classname>, o establecerla más tarde con <methodname>set_label()</methodname>.Hay dos maneras de establecer un grupo de botones de radio. La primera manera es crear los botones, y establecer sus grupos luego. Sólo los dos primeros constructores se usan. En el siguiente ejemplo, se crea una clase de ventana nueva llamada <classname>RadioButtons</classname> y luego se ubican tres botones de radio en ella:Hay un método para dibujar desde un <classname>Gdk::Pixbuf</classname> a un <classname>Cairo::Context</classname>. Un búfer <classname>Gdk::Pixbuf</classname> es un envoltorio útil alrededor de un grupo de píxeles, que puede leerse desde archivos y manipularse de varias maneras.Hay un ejemplo más complejo en examples/others/dnd.Hay un argumento opcional adicional: <placeholder-1/>Podría existir alguna ocasión en la que necesite modificar la lista de archivos usados recientemente. Por ejemplo, si un archivo se borra o renombra, necesitará actualizar la localización del archivo en la lista de archivos recientes para que no apunte a un lugar incorrecto. Puede actualizar la localización de un elemento usando <methodname>move_item()</methodname>.Hay mucho para pensar en este código no funcional. Primero, identifique a los grupos involucrados:Por lo tanto, el equivalente <classname>RefPtr</classname> de <type>Algo*</type> para un parámetro de un método es <type>const Glib::RefPtr&lt;Something&gt;&amp;</type>, y el equivalente de <type>const Algo*</type> es <type>const Glib::RefPtr&lt;const Something&gt;&amp;</type>.Estas son las barras de desplazamiento estándar. Sólo se deben ser usar para desplazar otro widget, como un <classname>Gtk::Entry</classname>, o un <classname>Gtk::Viewport</classname>, aunque generalmente es más fácil usar el widget <classname>Gtk::ScrolledWindow</classname> en la mayoría de los casos.Estas dependencias tienen sus propias dependencias, incluyendo las siguientes aplicaciones y bibliotecas:Estas interacciones nacen del hecho de que, entre otras cosas, una clase que hereda de <classname>sigc::trackable</classname> tendrá, por herencia, un objeto <classname>std::list</classname> que rastrea los «slots» creados por llamadas a <function>sigc::mem_fun()</function> y representa cualquiera de sus métodos no estáticos (en mayor detalle, mantiene una lista de retornos de llamada que anularán los «slots» conectados en su destrucción). Cada objeto <classname>sigc::slot</classname> también mantiene, a través de <classname>sigc::slot_rep</classname>, su propio objeto <classname>sigc::trackable</classname> para rastrear cualquier objeto <classname>sigc::connection</classname> al que necesite informarle su caída, y también tiene una función para deregistrarse de cualquier <classname>sigc::trackable</classname> en desconexión o destrucción. Los objetos <classname>sigc::signal</classname> también mantienen listas de «slots», que se actualizan mediante llamadas a su método <methodname>connect()</methodname> o llamadas a cualquier objeto <classname>sigc::connection</classname> relacionado a dicha conexión.Estas señales se comportan levemente diferentes. El valor que devuelve el manejador de señales indica si ha «manejado» completamente el evento. Si el valor es <literal>false</literal>, entonces <application>gtkmm</application> pasará el evento al próximo manejador de señales. Si el valor es <literal>true</literal>, entonces no se necesitará llamar a ningún otro manejador de señales.Estos widgets se usan principalmente para decorar o distribuir, por lo que a menudo no necesitará capturar sus eventos. Están destinados a no tener X-Window para mejorar su desempeño.Las cosas se arrastran desde las <literal>fuentes</literal> para soltarse en los <literal>destinos</literal>. Cada origen y destino tiene información acerca de los formatos de datos que puede recibir o enviar, proporcionada por elementos <classname>Gtk::TargetEntry</classname>. Un destino sólo aceptará un elemento arrastrado si ambos comparten un elemento <classname>Gtk::TargetEntry</classname> compatible. Las señales apropiadas se emitirán entonces, comunicándole a los manejadores de señales qué <classname>Gtk::TargetEntry</classname> se usó.Este archivo <filename>.defs</filename> describe a los tipos de enumeraciones y a sus valores posibles. Se genera mediante el script <filename>enum.pl</filename> que puede encontrar en la carpeta <filename>tools</filename> de glibmm. Por ejemplo, <placeholder-1/>Este archivo <filename>.defs</filename> describe a los objetos y a sus funciones. Se genera mediante el script <command>h2def.py</command> que puede encontrar en la carpeta <filename>tools/defs_gen</filename> de glibmm. Por ejemplo, <placeholder-1/>Esta variable <varname>PROGRAMNAME_LOCALEDIR</varname> se usará luego en el archivo <literal>Makefile.am</literal>, para definir una macro que se usará cuando inicialice <application>gettext</application> en su código fuente.Esto le permite a los enlaces entre lenguajes implementar sus propios equivalentes (como los constructores de C++), sin usar la función <function>*_new()</function>. Esto a menudo es necesario para poder instanciar realmente un GType derivado, para añadir sus propios ganchos para manejadores de señales y «vfuncs».Este libroEste libro asume un buen entendimiento sobre C++, y cómo crear programas en C++.Este libro explica conceptos clave sobre la API <application>gtkmm</application> de C++ para la creación de interfaces de usuario. También introduce los elementos principales de la interfaz de usuario («widgets»).Este libro explica conceptos clave sobre la API <application>gtkmm</application> de C++ para la creación de interfaces de usuario. También introduce los elementos principales de la interfaz de usuario («widgets»). A pesar de que se hace mención a las clases, constructores y métodos, estas no se explican en gran detalle. Por lo tanto, para obtener información completa sobre la API, diríjase a los enlaces en la documentación de referencia.Esto hace que <application>gtkmm</application> llame al método especificado siempre que no esté sucediendo nada más. Puede añadir una prioridad (los números más bajos indican prioridades más altas). Hay dos maneras de eliminar el manejador de señales: llamando a <methodname>disconnect()</methodname> en el objeto <classname>sigc::connection</classname>, o devolviendo <literal>false</literal> en el manejador de señales, que debe declararse como se indica a continuación:En este capítulo se presentan algunos de los aspectos más importantes de la codificación <application>gtkmm</application>. Que se validarán con un ejemplo de trabajo de código. Sin embargo, esta es sólo una pequeña muestra, por lo que es necesario leer otros capítulos para obtener más información importante.Esta clase implementa la ventana «Hello World». Deriva de <classname>Gtk::Window</classname> y tiene un único <classname>Gtk::Button</classname> como miembro. Se eligió usar el constructor para realizar todo el trabajo de inicialización de la ventana, incluyendo establecer las señales. Aquí está, sin los comentarios:Este comando construirá e instalará una serie de módulos y probablemente tarde mucho tiempo la primera vez. Después de la primera vez, sin embargo, debería ir mucho más rápido dado que sólo tendrá que reconstruir los archivos que han cambiado desde la última vez. Alternativamente, después de haber construido e instalado <application>gtkmm</application> por primera vez, lo podrá reconstruir por sí mismo (sin reconstruir todas sus dependencias) con el comando <command>jhbuild buildone gtkmm</command>.Este error del compilador podría tener este aspecto: <placeholder-1/> o este: <placeholder-2/>Fueron voluntarios los que crearon este documento, al igual que mucho otro software grandioso, gratuitamente. Si tiene conocimientos de cualquier aspecto de <application>gtkmm</application> que todavía no esté documentado, por favor considere contribuir a este documento.Este ejemplo añade una <classname>ToolPalette</classname> y una <classname>DrawingArea</classname> a una ventana y le permite al usuario arrastrar iconos de la paleta de herramientas al área de dibujo. La paleta de herramientas contiene varios grupos de elementos. Las cajas combinadas le permiten al usuario cambiar el estilo y la orientación de la paleta de herramientas.Este ejemplo permite copiar y pegar datos específicos de la aplicación, usando el objetivo estándar de texto. A pesar de que esto es simple, no es lo ideal porque no identifica los datos del <classname>Clipboard</classname> como un tipo particular.Este ejemplo crea un <classname>Gtk::EntryCompletion</classname> y lo asocia a un widget <classname>Gtk::Entry</classname>. Se usan un <classname>Gtk::TreeModel</classname> de entradas posibles para el completado y algunas acciones adicionales.Este ejemplo crea un botón con una imagen y una etiqueta.Este ejemplo crea una ventana con tres botones en una cuadrícula. Los dos primeros botones están en la fila superior, de izquierda a derecha. Se ha añadido un tercer botón bajo el primer botón, en una nueva fila más abajo, abarcando dos columnas.Este ejemplo crea dos programas ejecutables: <filename>socket</filename> y <filename>plug</filename>. La idea es que <filename>socket</filename> tenga una ventana de aplicación en la que se empotre un widget del programa <filename>plug</filename>. Dada la manera en la que este ejemplo está diseñado, <filename>plug</filename> debe estar en ejecución antes de iniciar <filename>socket</filename>. Para ver el ejemplo en acción, ejecute los siguientes comandos en orden desde la carpeta de ejemplos:Este ejemplo muestra una ventana con tres widgets de rango, todos conectados al mismo ajuste, junto con un par de controles para establecer algunos de los parámetros mencionados anteriormente y en la sección de ajustes, para que pueda ver cómo afectan la manera en la que estos widgets funcionan para el usuario.Este ejemplo tiene un widget <classname>Gtk::TreeView</classname>, con un modelo <classname>Gtk::ListStore</classname>.Este ejemplo implementa un contenedor con dos widgets hijos, uno encima del otro. Por supuesto, en este caso sería mucho más simple usar sólo una <classname>Gtk::Box</classname> vertical.Este ejemplo implementa un widget que dibuja un triángulo de Penrose.Este ejemplo es idéntico al del <classname>ListStore</classname>, pero usa <methodname>TreeView::append_column_editable()</methodname> en lugar de <methodname>TreeView::append_column()</methodname>.Este ejemplo es muy parecido al ejemplo del <classname>ListStore</classname>, pero deriva un <classname>TreeView</classname> personalizado para sobrecargar al <literal>button_press_event</literal>, y también encapsular al código del modelo de árbol en la clase derivada. Consulte la sección <link linkend="sec-treeview-contextmenu">TreeView: menú contextual emergente</link>.Este ejemplo es muy parecido al ejemplo del <classname>TreeStore</classname>, pero tiene dos columnas adicionales que indican si la fila se puede arrastrar, y si puede recibir filas arrastradas y soltadas. Usa un <classname>Gtk::TreeStore</classname> derivado, que sobrecarga las funciones virtuales como se describe en la sección <link linkend="sec-treeview-draganddrop">TreeView: arrastrar y soltar</link>.Este ejemplo es muy similar al ejemplo del <classname>ListStore</classname>, pero usa el modelo <classname>Gtk::TreeStore</classname> en su lugar, y le añade hijos a las filas.Este ejemplo señala un poco la diferencia entre los métodos en espera y los de tiempo de espera. Si necesita métodos que se llamen periódicamente, y la velocidad no es muy importante, entonces quiere métodos de tiempo de espera. Si quiere métodos que se llamen tan a menudo como sea posible (como calcular un fractal en segundo plano), entonces use métodos de espera.Este ejemplo alinea a la derecha un botón en una ventana mediante el uso de un widget <classname>Alignment</classname>.Este ejemplo muestra un widget <classname>Gtk::Entry</classname> con un icono de búsqueda del almacén, e imprime texto en la terminal cuando se pulsa el icono.Este ejemplo muestra un widget <classname>Gtk::Entry</classname> con una barra de progreso.Este ejemplo mustra cómo cargar un archivo <application>Glade</application> en tiempo de ejecución y acceder a los widgets mediante una clase derivada.Este ejemplo usa <classname>Gtk::Entry</classname>. También tiene dos <classname>CheckButton</classname>, con los que puede conmutar las opciones «editable» y «visible».Los métodos generados desde _WRAP_METHOD() podrán entonces lanzar esta excepción con la opción «errthrow».Esto tiene las siguientes ventajas: <placeholder-1/>Esto involucra una variedad de herramientas, algunas de ellas obsoletas, pero que al menos funcionan, y que varios proyectos han usado exitosamente.Esto implica el uso de las clases <classname>Gtk::ActionGroup</classname>, <classname>Gtk::Action</classname>, y <classname>UIManager</classname>, todas las cuales deben instanciarse a través de sus métodos <methodname>create()</methodname>, que devuelven <classname>RefPtr</classname>.Este es un ejemplo funcional completo que define y usa señales personalizadas.Esto queda demostrado en el ejemplo del menú emergente personalizado.Esto se demuestra en el ejemplo «drag_and_drop».Esto es fácil de corregir en la biblioteca de C, así que envíe un parche al mantenedor pertinentes.Es como el ejemplo simple, pero <placeholder-1/>Este es uno de los lugares en los que se muestra realmente la belleza de C++. Uno no consideraría heredar un widget de GTK+ simplemente para reemplazar a su método de acción; es mucho problema. En GTK+, casi siempre se usan señales para realizar las tareas, a menos que se estuviera escribiendo un widget nuevo. Pero, dado que reemplazar métodos es tan fácil en C++, es enteramente práctico (y razonable) heredar de un botón para ese propósito.Esta es la declaración del método <methodname>pack_start()</methodname>.Esto no es un asunto único de <application>gtkmm</application> o de IGU. <application>gtkmm</application> usa <application>libsigc++</application> para implementar sus envoltorios de proxy para el sistema de señales de <application>GTK+</application>, pero para las señales nuevas que no son de GTK+, puede crear señales de C++ puras, usando la plantilla <classname>sigc::signal&lt;&gt;</classname>.Esta macro puede usarse para envolver estructuras que no se ajustan a ninguna categoría especializada.Esta macro crea un constructor con argumentos, equivalente a una función de C <function>*_new()</function>. En realidad no llamará a la función <function>*_new()</function>, sino que simplemente creará un constructor equivalente con los mismos tipos de argumentos. Toma una firma de constructor de C++ y un nombre de función de C.Esta macro crea un constructor predeterminado sin argumentos.Esta macro declara un envoltorio para una estructura que no es <classname>GObject</classname>, registrada con <function>g_boxed_type_register_static()</function>.Esta macro declara un envoltorio para una estructura opaca con conteo de referencias. El envoltorio de C++ no puede instanciarse directamente y sólo lo puede usar <classname>Glib::RefPtr</classname>.Esta macro declara un envoltorio para una estructura asignable simple como <classname>GdkRectangle</classname>. Es similar a <function>_CLASS_BOXEDTYPE</function>, pero la estructura de C no se asigna dinámicamente.Esta macro declara un envoltorio de un tipo que deriva de <classname>GObject</classname>, pero cuyo envoltorio no deriva de <classname>Gtk::Object</classname>.Esta macro declara un envoltorio para un tipo que deriva de <classname>GTypeInterface</classname>.Esta macro declara un envoltorio para un tipo cuyo envoltorio deriva de <classname>Gtk::Object</classname>, como un widget o un diálogo.Esta macro declara un envoltorio para una estructura opaca que tiene funciones «copy» y «free». Las funciones «new», «copy» y «free» se usarán para instanciar el constructor predeterminado, copiar el constructor y el destructor.Esta macro genera una enum de C++ para envolver una enum de C. Debe especificar el nombre de C++ que quiere y el nombre de la enum de C subyacente.Esta macro genera una clase de excepción de C++, derivada de Glib::Error, con una enum Code y un método code(). Debe especificar el nombre de C++ que quiere, el nombre de la enum de C correspondiente, y el prefijo de los valores de la enum de C.Esta macro genera código de inicialización para la interfaz.Esta macro genera la señal de C++ con el estilo de libsigc++ para envolver una señal GObject de C. En realidad genera un método de acceso público, como <function>signal_clicked()</function>, que devuelve un objeto sustituto. <function>gmmproc</function> usa el archivo .defs para descubrir los tipos de parámetro de C y los archivos de conversión .m4 para descubrir conversiones de tipo adecuadas.Esta macro genera el método de C++ que envuelve una propiedad GObject de C. Debe especificar el nombre de la propiedad y el tipo de C++ que quiere para la propiedad. <command>gmmproc</command> usa el archivo .defs para descubrir el tipo de C y el archivo de conversión .m4 para descubrir conversiones de tipo apropiadas.Esta macro genera el método de C++ para envolver una función de C.Esta macro genera el método de C++ que envuelve una función virtual de C.Esta macro es similar a <function>_WRAP_METHOD()</function>, pero sólo genera la documentación de un método de C++ que envuelve una función de C. Úsela cuando debe escribir el método a mano, pero quiere usar la documentación que se crearía si el método se generara.Esta macro se usará cuando inicialice <literal>gettext</literal> en su código fuente.Esto significa que cualquier método que tome un argumento <type>const Glib::RefPtr&lt;BaseType&gt;</type> también puede tomar un <type>const Glib::RefPtr&lt;DerivedType&gt;</type>. La conversión es implícita, al igual que lo sería con un puntero normal.Este programa contiene una sola clase, <classname>MyArea</classname>, que es una subclase de <classname>Gtk::DrawingArea</classname> y contiene una función miembro <methodname>on_draw()</methodname>. Esta función se llama siempre que la imagen en el área de dibujo deba redibujarse. Se le pasa un puntero <classname>Cairo::RefPtr</classname> al <classname>Cairo::Context</classname> que se usa para el dibujo. El código de dibujo real establece el color que queremos usar para dibujar usando <methodname>set_source_rgb()</methodname>, que toma argumentos definiendo los componentes de rojo, verde, y azul del color deseado (los valores válidos se hallan entre 0 y 1). Después de establecer el color, creamos un camino nuevo usando las funciones <methodname>move_to()</methodname> y <methodname>line_to()</methodname>, y luego lo rellenamos usando <methodname>stroke()</methodname>.Esto proporciona una estructura de carpetas para los archivos de fuentes .hg y .ccg, y los archivos .h y .cc generados; con archivos de cabecera <filename>filelist.am</filename> de Automake que pueden especificar la variedad de archivos en uso, en términos de variables de Automake genéricas. La estructura de carpetas generalmente se ve así, después de haber renombrado las carpetas apropiadamente: <placeholder-1/>Esto requiere que se observen una cantidad de reglas cuando escribe programas de múltiples hilos usando <application>gtkmm</application>. Estas se exponen abajo, pero un punto a destacar es que se requiere cuidado adicional cuando deriva clases de <classname>sigc::trackable</classname>, porque los efectos no son intuitivos (consulte particularmente los puntos 4 y 5 debajo).Esta sección describe principalmente qué puede esperar en un sistema Linux, cuando usa el <ulink url="http://www.gnu.org/software/gdb/">depurador gdb</ulink>.Esta sección es simplemente un acopio de sabiduría, pautas generales de estilo y consejos para crear aplicaciones en <application>gtkmm</application>.Esta aplicación simple dibuja una curva con Cairo y muestra los puntos de control para cada punta de la curva.Este ejemplo simple muestra cómo cargar un archivo <application>Glade</application> en tiempo de ejecución y acceder a los widgets con <application>Gtk::Builder</application>.Esto le dice a gmmproc que el <function>*_new()</function> de C tiene un parámetro GError** final que debe ignorarse.Esta variable debe mencionar el nombre de la biblioteca correcta, y este nombre de biblioteca debe usarse para formar los nombres de variables <varname>_SOURCES</varname>, <varname>_LDFLAGS</varname>, y <varname>_LIBADD</varname>. Está permitido usar variables sustituidas por <varname>configure</varname>, como <varname>@SOMETHINGMM_API_VERSION@</varname> como parte de los nombres de las variables.Tiempos de esperaTiempos de espera, E/S y funciones en esperaPara acceder a un widget, por ejemplo para mostrar (<methodname>show()</methodname>) un diálogo, use el método <methodname>get_widget()</methodname> proporcionándole el nombre del widget. Este nombre debe especificarse en la ventana Propiedades de <application>Glade</application>. Si no se encontró el widget, o si es del tipo incorrecto, se asignará 0 al puntero. <placeholder-1/>Para lograr esto, debe usar los métodos <classname>Gtk::TreeView</classname> <methodname>insert_column()</methodname> y <methodname>append_column()</methodname> normales, y luego usar <methodname>get_column_cell_renderer()</methodname> para obtener el <classname>Gtk::CellRenderer</classname> que usa esa columna.Para añadir un archivo nuevo a la lista de documentos recientes, en el caso más simple, sólo necesita proporcionar su URI. Por ejemplo:Para añadir widgets al área de acción, use el método <methodname>add_action_widget()</methodname>. Serán empaquetados junto a los botones predeterminados. Use el método <methodname>remove_action_widget()</methodname> para borrar los widgets.Para iniciar nuestra introducción a <application>gtkmm</application>, vamos a empezar con el programa más simple posible. Este programa va a crear una ventana vacía de 200 x 200 píxeles.Para cambiar la selección, especifique un <classname>Gtk::TreeModel::iterator</classname> o un <classname>Gtk::TreeModel::Row</classname>, así:Para cambiar el valor mostrado, use el método <methodname>set_fraction()</methodname>, pasándole un <type>double</type> entre 0.0 y 1.0 para proporcionarle el porcentaje nuevo.Para controlar qué filas pueden seleccionarse, use el método <methodname>set_select_function()</methodname>, proporcionándole un retorno de llamada <classname>sigc::slot</classname>. Por ejemplo:Para convencerse de que ha hecho lo correcto, tal vez quiera añadir una traducción para una localización nueva. Para hacer eso, vaya a la subcarpeta <filename>po</filename> de su proyecto y ejecute el siguiente comando: <placeholder-1/>Para definir un atajo para la navegación por teclado, ponga un guión bajo antes de uno de los caracteres y especifique <literal>true</literal> para el parámetro opcional <literal>mnemonic</literal>. Por ejemplo:Para determinar la página actualmente visible, use el método <methodname>get_current_page()</methodname> y pásele el resultado a <methodname>get_nth_page()</methodname>, que le devuelve un puntero al widget en sí. Para cambiar mediante programación la página actual, use el método <methodname>set_current_page()</methodname>.Para determinar qué tecla se presionó o soltó, lea el valor de <varname>GdkEventKey::keyval</varname> y compárelo con una constante en el archivo de cabecera <filename>&lt;gdk/gdkkeysyms.h&gt;</filename>. Los estados de las teclas modificadoras (mayús, control, etc.) están disponibles como banderas de bits en <varname>GdkEventKey::state</varname>.Para descubrir la página visible actual, use el método <methodname>get_current_page()</methodname>. Esto devuelve el número de página. Después llame a <methodname>get_nth_page()</methodname> con ese número le dará un puntero al widget hijo en sí.Para hacer cualquier dibujo en <application>Gtkmm</application> con Cairo, primero debe crear un objeto <classname>Cairo::Context</classname>. Esta clase contiene a todos los parámetros del estado de gráficos que describen cómo se dibujará. Esto incluye información como el ancho de línea, color, la superficie a la que dibujar, y muchas otras cosas. Esto permite a las funciones de dibujo en si tomar menos argumentos para simplificar la interfaz. En <application>gtkmm</application>, un <classname>Cairo::Context</classname> se crea llamando a la función <methodname>Gdk::Window::create_cairo_context()</methodname>. Dado que los contextos de Cairo son objetos contados por referencia, esta función devuelve un objeto <classname>Cairo::RefPtr&lt;Cairo::Context&gt;</classname>Para hacer esto, debe llamar al método <methodname>pulse()</methodname> a intervalos regulares. También puede elegir el tamaño del paso con el método <methodname>set_pulse_step()</methodname>.Para dibujar una elipse, puede escalar la matriz de transformación actual en cantidades diferentes en las direcciones de X e Y. Por ejemplo, para dibujar una elipse con un centro en <varname>x</varname>, <varname>y</varname>, y de tamaño <varname>width</varname>, <varname>height</varname>: <placeholder-1/>Para activar esta funcionalidad, cree un objeto <classname>EntryCompletion</classname> y proporcióneselo al widget <classname>Entry</classname> mediante el método <methodname>set_completion()</methodname>.Para descubrir qué filas ha seleccionado el usuario, obtenga el objeto <classname>Gtk::TreeView::Selection</classname> del <classname>TreeView</classname>, así:Para descubrir qué objetivos están actualmente disponibles en el <classname>Clipboard</classname> para pegar, llame al método <methodname>request_targets()</methodname>, especificando un método al que llamar con la información. Por ejemplo:Para descubrir qué tipo de manejador de señales puede conectar a una señal, puede buscarlo en la documentación de referencia en el archivo de cabecera. Aquí hay un ejemplo de una declaración de señal que puede ver en las cabeceras de <application>gtkmm</application>:Para forzarlo a encajar en el <literal>step_increment</literal> más cercano, use <methodname>set_snap_to_ticks()</methodname>.Para instanciar una <classname>Gtk::MenuBar</classname> o una <classname>Gtk::Toolbar</classname>, a la que en realidad puede mostrar, debe usar el método <methodname>UIManager::get_widget()</methodname>, y luego añadirle el widget a un contenedor. Por ejemplo:Para instanciar sólo una ventana, o sólo uno de los widgets hijo, puede especificar el nombre del widget como segundo parámetro. Por ejemplo, <placeholder-1/>Para buscar archivos usados recientemente, <classname>RecentManager</classname> proporciona varias funciones. Para buscar un elemento específico por su URI, puede usar la función <methodname>lookup_item()</methodname>, que devolverá una clase <classname>RecentInfo</classname>. Si el URI especificado no existe en la lista de archivos recientes, <methodname>lookup_item()</methodname> arroja una excepción <classname>RecentManagerError</classname>. Por ejemplo:Para que el <classname>SpinButton</classname> «salte» entre sus límites superior e inferior, use el método <methodname>set_wrap()</methodname>.Para obtener una instancia <application>gtkmm</application> desde una instancia C GObject, use la función Glib::wrap(). Por ejemploPara empaquetar widgets en un diálogo personalizado, debe empaquetarlos en la <classname>Gtk::Box</classname>, disponible a través de <methodname>get_content_area()</methodname>. Para simplemente añadirle un <classname>Button</classname> a la parte inferior del <classname>Dialog</classname>, puede usar el método <methodname>add_button()</methodname>.Para que el usuario no pueda introducir caracteres no numéricos al cuadro de entrada, pásele <literal>true</literal> al método <methodname>set_numeric()</methodname>.Para cambiar la página seleccionada mediante programación, use el método <methodname>set_current_page()</methodname>.Para recibir los eventos del teclado, primero debe llamar a la función <methodname>Gtk::Widget::add_events()</methodname> con una máscara de bits de los eventos en los que esté interesado. El manejador de señales de eventos recibirá un argumento que dependerá del tipo de evento. Para eventos del teclado, es un <type>GdkEventKey*</type>. Como de describe en el <link linkend="sec-xeventsignals">apéndice</link>, el manejador de señales de eventos devuelve un valor <type>bool</type> para indicar que se maneja completamente la señal (<literal>true</literal>) o permitir la propagación del evento (<literal>false</literal>).Para reproducir más de una columna del modelo en una columna de vista, necesita crear el widget <classname>TreeView::Column</classname> manualmente, y usar <methodname>pack_start()</methodname> para añadirle las columnas del modelo.Para responder a la pulsación del usuario en una fila o un rango de filas, conéctese a la señal así:Para recuperar el estado de un <classname>ToggleButton</classname>, puede usar el método <methodname>get_active()</methodname>. Esto devuelve <literal>true</literal> si el botón está «abajo». También puede establecer el estado del botón conmutador con <methodname>set_active()</methodname>. Tenga en cuenta que, si hace esto, y el estado efectivamente cambia, hace que se emita la señal «clicked». Esto normalmente será lo que quiera.Para ver dónde se lanza la excepción, puede usar el comando <userinput>catch throw</userinput> de <application>gdb</application>. <placeholder-1/>Para establecer el título de una página, use el método <methodname>set_page_title()</methodname>. Las imágenes de cabecera y de lado de una página se pueden establecer con los métodos <methodname>set_page_header_image()</methodname> y <methodname>set_page_side_image()</methodname>.Para configurar <application>jhbuild</application>, siga las instrucciones básicas de instalación del <ulink url="http://developer.gnome.org/jhbuild/unstable/">manual de jhbuild</ulink>. Después de que lo haya instalado, deberá copiar la configuración de ejemplo de <application>jhbuild</application> a su carpeta personal ejecutando el siguiente comando desde la carpeta de <application>jhbuild</application>: <screen>$ cp examples/sample.jhbuildrc ~/.jhbuildrc</screen>Para mostrar el menú contextual, use el método <methodname>popup()</methodname> del <classname>Gtk::Menu</classname>, proporcionándole el identificador del botón y el tiempo de activación, como los proporciona la señal <literal>button_press_event</literal> que, de todos modos, deberá manejar. Por ejemplo:Para simplificar la compilación, se usa <literal>pkg-config</literal>, que está presente en todas las instalaciones correctas de <application>gtkmm</application>. Este programa «sabe» qué opciones de compilación son necesarias para compilar los programas que usan <application>gtkmm</application>. La opción <literal>--cflags</literal> hace que <literal>pkg-config</literal> devuelva la lista de carpetas en las que el compilador buscará los archivos de cabecera; la opción <literal>--libs</literal> solicita la lista de bibliotecas a las que el compilador enlazará y las carpetas en las que encontrarlas. Intente ejecutarlo desde su intérprete de comandos para ver los resultados en su sistema.Para especificar que algún texto en el búfer deba tener un formato especial, defina una etiqueta que contenta esa información de formato, y luego aplíquela a la región de texto. Por ejemplo, para definir la etiqueta y sus propiedades:Para usar una instancia de <application>gtkmm</application> con una función C que requiere una instancia GObject C, use la función <function>gobj()</function> para obtener un puntero a la instancia GObject subyacente. Por ejemploPara solucionar temporalmente esto, puede escribir un comentario en el código fuente justo antes de la cadena, diciéndole a los traductores que usen el carácter especial si está disponible en sus lenguajes. Para el inglés, después puede hacer una traducción a inglés americano <filename>en_US.po</filename> que use ese carácter especial.Botones conmutablesBotón ConmutableReferencia de ToolItemReferencia de ToolItemGroupToolPaletteEjemplo de ToolPaletteReferencia de ToolPaletteConsejoReferencia de consejosConsejosLos consejos son pequeñas ventanas de información que aparecen cuando deja su puntero sobre un widget por unos segundos. Use <methodname>set_tooltip_text()</methodname> para establecer una cadena nueva como consejo en cualquier <classname>Widget</classname>. Los <classname>Gtk::ToolItem</classname> no son <classname>Widget</classname>s, pero tienen el mismo método por convenio. <classname>Gtk::Tooltip</classname> es para un uso de los consejos más avanzado, como mostrar una imagen junto al texto.TreeModel::iterator iter = refTreeSelection-&gt;get_selected();
if(iter) //If anything is selected
{
  TreeModel::Row row = *iter;
  //Do something with the row.
}Referencia de TreeModelSortReferencia de TreeSortableTreeStoreTreeStore, para una jerarquíaTreeView: arrastrar y soltarTreeView: celdas editablesTreeView - ListStoreTreeView: menú de contexto emergenteTreeView - TreeStoreQt de Trolltech es el competidor más cercano de <application>gtkmm</application>, por lo que merece discusión.Pruebe a ejecutar este ejemplo e incrementar la carga del sistema. La barra de progreso superior incrementará progresivamente, la inferior irá más lentamente.Intente compilarla y ejecutarla antes de continuar. Debería ver algo así:Típicamente la biblioteca envoltorio se llamaría libsomethingmm. Se puede empezar copiando el <ulink url="http://git.gnome.org/cgit/mm-common/tree/skeletonmm">esqueleto del árbol de código fuente</ulink> desde el módulo mm-common. <placeholder-1/>Los cambios en la IU pueden observarse más rápidamente, por lo se pueden mejorar las IU.UIManagerNo se pueden predeclarar estructurasDesafortunadamente, la integración con iostreams estándar no es completamente infalible. <application>gtkmm</application> convierte <classname>Glib::ustring</classname> a una codificación específica de la localización (que generalmente no es UTF-8) si las dirige a un <classname>ostream</classname> con <function>operator&lt;&lt;</function>. De igual manera, recuperar <classname>Glib::ustring</classname> de <classname>istream</classname> con <function>operator&gt;&gt;</function> causa una conversión en la dirección opuesta. Pero este esquema se rompe si usa una <classname>std::string</classname>, por ejemplo introduciendo texto desde un flujo a una <classname>std::string</classname> y luego convirtiéndola implícitamente a una <classname>Glib::ustring</classname>. Si la cadena contenía caracteres no ASCII y la localización actual no está codificada en UTF-8, el resultado es una <classname>Glib::ustring</classname> corrupta. Puede solucionar temporalmente esto con una conversión manual. Por ejemplo, para recuperar la <classname>std::string</classname> de un <classname>ostringstream</classname>: <placeholder-1/>Unix y LinuxA menos que su contenedor sea una ventana de nivel superior que derive de <classname>Gtk::Window</classname>, probablemente también deba llamar a <methodname>Gtk::Widget::set_has_window(false)</methodname> en su constructor. Esto significa que su contenedor no crea su propia <classname>Gdk::Window</classname>, sino que usa la de su padre (note la diferencia entre <classname>Gtk::Window</classname> y <classname>Gdk::Window</classname>). Si su contenedor no necesita su propia  <classname>Gdk::Window</classname>, y no deriva de <classname>Gtk::Window</classname>, también debe reemplazar el método <methodname>on_realize()</methodname> como se describe en la sección <link linkend="sec-custom-widgets">Widgets personalizados</link>. Y, a menos que su contenedor dibuje directamente sobre la <classname>Gdk::Window</classname> subyacente, probablemente deba llamar a <methodname>set_redraw_on_allocate(false)</methodname> para mejorar el rendimiento.A diferencia de la solución Unicode de Windows UCS-2, esto no requiere ninguna opción especial de compilación para procesar cadenas literales, y no resulta en que los ejecutables y bibliotecas Unicode sean incompatibles con las ASCII.A diferencia de los otros widgets en esta sección, los paneles no contienen un widget hijo, sino dos, uno en cada panel. Por lo tanto, debe usar los métodos <methodname>add1()</methodname> y <methodname>add2()</methodname> en vez de <methodname>add()</methodname>.Palabras poco frecuentesPolíticas de ActualizaciónActualice su <literal>DISTCLEANFILES</literal>: <placeholder-1/>Use <classname>Glib::Dispatcher</classname> para invocar las funciones de <application>gtkmm</application> desde hilos de trabajo (esto se explica con má detalle en la próxima sección).Use <methodname>Gtk::Builder::get_widget_derived()</methodname> así: <placeholder-1/>Use <application>autoconf</application> y <application>automake</application> de GNU. Son sus amigos :). <application>Automake</application> examina archivos de C, determina cómo dependen entre sí, y genera un <filename>Makefile</filename> para que los archivos puedan compilarse en el orden correcto. <application>Autoconf</application> permite la configuración automática de la instalación de software, manipulando un gran número de peculiaridades de cada sistema para incrementar la portabilidad.Use los métodos <methodname>append_page()</methodname>, <methodname>prepend_page()</methodname> e <methodname>insert_page()</methodname> para añadir páginas con pestañas al <literal>Notebook</literal>, proporcionándoles el widget hijo y el nombre de la pestaña.Use los métodos <methodname>append_page()</methodname>, <methodname>prepend_page</methodname> e <methodname>insert_page()</methodname> para añadirle páginas al <classname>Assistant</classname>, proporcionándole el widget hijo por cada página.Usa el último parámetro GError** de la función de C para lanzar una excepción.Usa el último parámetro GError** de la función virtual de C (si existe) para lanzar una excepción.Use estas macros si está envolviendo una estructura simple o un tipo en caja que proporciona acceso directo a sus miembros de datos, para crear métodos de acceso y modificación para estos.Use estas macros para proporcionar métodos de acceso y modificación para un miembro de datos que es de tipo puntero automáticamente. Para la función de acceso, creará dos métodos, uno constante y otro no constante.Use estas macros para proporcionar métodos de acceso y modificación para un miembro de datos que es de tipo <classname>GObject</classname> que debe referenciarse antes de devolverse.Usado junto con la opción <literal>slot_name</literal> para especificar el nombre de la función de devolución de llamada adhesiva que maneja la extracción del «slot» y su llamada. La dirección de esta devolución de llamada también se pasa a la función de C que el método envuelve.Métodos útilesUsar ajustes de la manera fácilUsar Glib::DispatcherUsar un widget de <application>gtkmm</application>Usar un modeloUsar widgets derivadosUsar caracteres no ASCII en cadenasUsar la versión de git de <application>gtkmm</application>VineTambién se asume que está usando autotools (por ejemplo, <application>automake</application> y <application>autoconf</application>) para construir su proyecto, y que está usando <ulink url="http://git.gnome.org/browse/gnome-common/tree/autogen.sh"><literal>./autogen.sh</literal> desde <application>gnome-common</application></ulink>, que, entre otras cosas, se ocupa de parte de la inicialización de <application>intltool</application>.También se habla del widget <classname>Gtk::Paned</classname>, que le permite dividir una ventana en dos «paneles» separados. El widget, en realidad, contiene dos widgets hijos, pero el número es fijo, por lo que parece apropiado.Como se mencionó, la señal <literal>clicked</literal> del botón está esperando llamar a un método sin argumentos. Todas las señales tienen requerimientos como este: no puede enganchar una función con dos argumentos a una señal que no espera ninguno (a menos que use un adaptador, como <function>sigc::bind()</function>, por supuesto). Por lo tanto, es importante saber qué tipo de manejador de señales se esperará que conecte a una señal dada.Se creó un grupo nuevo simplemente declarando una variable, <literal>group</literal>, del tipo <classname>Gtk::RadioButton::Group</classname>. Luego, se hicieron tres botones de radio, usando un constructor para hacer que cada uno sea parte de <literal>group</literal>.Se hace una llamada a <methodname>Cairo::Context::scale()</methodname>, pasándole la anchura y altura del área de dibujo. Esto escala el sistema de coordenadas de espacio del usuario de tal manera que la anchura y altura del widget correspondan ambas a 1.0 «unidades». No hay una razón en particular para escalar el sistema de coordenadas en este caso, pero a veces, puede hacer las operaciones de dibujo más fáciles.Se deben mencionar todos los archivos <filename>.hg</filename> y <filename>.ccg</filename> en el archivo <filename>skeleton/src/filelist.am</filename>, típicamente en la variable <varname>files_hg</varname>.Ahora se usa std::vector en muchos métodos en vez de los tipos intermedios *Handle para hacer a la API más clara.Ahora se deben crear los primeros archivos <filename>.hg</filename> y <filename>.ccg</filename>, para envolver uno de los objetos en la biblioteca de C. Ya existen un par de archivos de fuentes de ejemplo: <filename>skeleton.ccg</filename> y <filename>skeleton.hg</filename>. Cree copias de estos archivos si es necesario.Luego, se le engancha un manejador de señales a la señal <literal>clicked</literal> de <literal>m_button</literal>. Esto imprime nuestro amigable saludo a <literal>stdout</literal>.Se indicó a <application>gtkmm</application> que colocase los tres <classname>RadioButton</classname> en el mismo grupo obteniéndolo con <methodname>get_group()</methodname> y usando <methodname>set_group()</methodname> para indicarle a los otros <classname>RadioButton</classname> que compartan ese grupo.Ahora se explicará cada línea del ejemploNos encantaría que nos informara sobre cualquier problema que encuentre aprendiendo <application>gtkmm</application> con este documento, y apreciaríamos cualquier información sobre mejoras en el mismo. Consulte la sección <link linkend="chapter-contributing">contribuir</link> para obtener más información.Se engancha al objeto <classname>Gtk::Button</classname> llamado <varname>button</varname>.Ahora ha aprendido lo suficiente para ver un ejemplo real. De acuerdo con una antigua tradición de la informática, se introducirá la aplicación Hola Mundo en <application>gtkmm</application>:¿Qué pasa si un widget reconfigura los campos <parameter>upper</parameter> o <parameter>lower</parameter> de su <classname>Adjustment</classname>, como cuando un usuario le añade más texto a un widget de texto? En este caso, emite la señal <literal>changed</literal>.¿Cuál es la diferencia entre el espaciado (establecido cuando se crea la caja) y el relleno (establecido cuando se empaquetan los elementos)? El espaciado se añade entre objetos, y el relleno a cada lado del widget. La siguiente figura debería aclararlo:Cuando <varname>pixbuf</varname> salga del alcance, un <methodname>unref()</methodname> sucederá en segundo plano y ya no necesitará preocuparse más de él. No hay <literal>new</literal>, por lo que no hay <literal>delete</literal>.Cuando un constructor debe escribirse a mano parcialmente porque, por ejemplo, los parámetros de la función de C <function>*_new()</function> no corresponden directamente a las propiedades del objeto, o porque la función de C <function>*_new()</function> hace más que llamar a <function>g_object_new()</function>, la macro <function>_CONSTRUCT()</function> se puede usar en el archivo .ccg para ahorrar trabajo. La macro <function>_CONSTRUCT()</function> toma una serie de nombres y valores de propiedades. Por ejemplo, de <filename>button.ccg</filename>: <placeholder-1/>Cuando un destino acepta un elemento arrastrado, se emiten ciertas señales, dependiendo de qué acción se ha seleccionado. Por ejemplo, el usuario podría haber mantenido presionada la tecla <keycap>Mayús</keycap> para especificar un <literal>movimiento</literal> en vez de una <literal>copia</literal>. Recuerde que el usuario sólo puede seleccionar las acciones que ha especificado en sus llamadas a <methodname>drag_dest_set()</methodname> y <methodname>drag_source_set()</methodname>.Cuando se aborta un programa por una excepción de C++ no manejada, a veces es posible usar un depurador para encontrar el lugar en el que la excepción se lanzó. Esto es más difícil de lo normal si un manejador de señales lanzó la excepción.Cuando derive de un <classname>Gtk::Container</classname>, debe reemplazar los siguientes métodos virtuales: <placeholder-1/>Cuando derive de <classname>Gtk::Widget</classname>, debe reemplazar los siguientes métodos virtuales. No necesita reemplazar los métodos marcados como (opcional) en todos los widgets personalizados. Los métodos de la clase base pueden ser apropiados. <placeholder-1/>Cuando el botón emita su señal <literal>clicked</literal>, se llamará a <methodname>on_button_clicked()</methodname>.Cuando la aplicación se ejecuta, la biblioteca <application>gettext</application> verifica la carpeta de sistema para comprobar si hay un archivo <filename>.mo</filename> para el entorno de localización del usuario (puede establecer la localización, por ejemplo, con «export LANG=de_DE.UTF-8» desde una consola bash). Más tarde, cuando el programa alcance una llamada a <literal>gettext</literal>, buscará la traducción de la cadena particular. Si no encuentra ninguna, usará la cadena original.Cuando el ratón esté sobre el botón y el botón del ratón se presione, se llamará a <methodname>on_button_press()</methodname>.Cuando el usuario pide copiar datos, debe decirle al <classname>Clipboard</classname> qué objetivos están disponibles y proporcionar los métodos de retorno de llamada que puede usar para obtener los datos. En este punto, debe almacenar una copia de los datos, para proporcionarla cuando el portapapeles llame a su método de retorno de llamada en respuesta a la acción de pegar.Cuando el usuario pide pegar datos desde el <classname>Clipboard</classname>, debe pedir un formato específico y proporcionar un método de retorno de llamada que se llamará con los datos en sí. Por ejemplo:Cuando el usuario introduce texto arbitrario, puede no ser suficiente conectar la señal <literal>changed</literal>, que se emite una vez por cada carácter introducido. No se emite cuando el usuario pulsa la tecla Intro. Pulsar la tecla Intro o mover el foco del teclado a otro widget puede señalar que el usuario ha terminado de introducir texto. Para notificarse de estos eventos, conecte las señales <literal>key_press_event</literal> y <literal>focus_out_event</literal> del <classname>Entry</classname>, así <placeholder-1/> Se emiten tanto las señales <literal>Changed</literal> del <classname>ComboBox</classname> como del <classname>Entry</classname> por cada cambio. No importa a cuál se conecta. Pero sólo la señal <literal>focus_out_event</literal> del <classname>Entry</classname> es útil aquí.Cuando use <function>_CLASS_GOBJECT()</function>, los constructores deben declararse protegidos (en lugar de públicos) y cada constructor debe tener un <function>_WRAP_CREATE()</function> correspondiente en la sección pública. Esto evita que la clase se instancie sin usar un <classname>RefPtr</classname>. Por ejemplo: <placeholder-1/>Cuando usa un <classname>Gtk::TreeStore</classname>, las filas pueden tener filas hijas, que a su vez pueden tener sus propios hijos. Use <methodname>Gtk::TreeModel::Row::children()</methodname> para obtener el contenedor de las <classname>Row</classname> hijas: <placeholder-1/>Cuando use esta simple sobrecarga <methodname>append_column()</methodname>, el <classname>TreeView</classname> mostrará los datos del modelo con un <classname>CellRenderer</classname> apropiado. Por ejemplo, las cadenas y los números se muestran en un simple widget <classname>Gtk::Entry</classname>, y los booleanos en un <classname>Gtk::CheckButton</classname>. Esto es normalmente lo que necesita. Para otros tipos de columnas, debe conectar un retorno de llamada que convierta su tipo en una cadena representativa, con <methodname>TreeViewColumn::set_cell_data_func()</methodname>; o derivar un <classname>CellRenderer</classname> personalizado. Tenga en cuenta que no se soporta el tipo «(unsigned) short» de manera predeterminada: puede usar como tipo de columna «(unsigned) int» o «(unsigned) long» en su lugar.Cuando descarga <application>jhbuild</application> desde el repositorio git, obtiene varios archivos <filename>.module</filename>, especificando las dependencias entre módulos. De manera predeterminada, <application>jhbuild</application> no usa las versiones descargadas de estos archivos, sino que lee las últimas en el repositorio git. Esto generalmente es lo que quiere. Si no es así, use la variable <varname>use_local_modulesets</varname> en <filename>.jhbuildrc</filename>.Cuando seleccione una opción de la lista desplegable, el valor de esta columna se pondrá en el widget <classname>Entry</classname>.Cuando escriba en el «entry», se emitirá un evento de liberación de tecla, que primero irá a la ventana superior (<classname>Gtk::Window</classname>), dado que hay un manejador de eventos establecido para que se llame antes, y ese es el que se llama primero (<methodname>windowKeyReleaseBefore()</methodname>). Después se llama al manejador de eventos predeterminado (al que se ha sobrecargado), y luego se envía el evento al widget que tiene el foco, el <classname>Entry</classname> en el ejemplo y, dependiendo de si lo dejamos propagar o no, puede alcanzar los manejadores de eventos del <classname>Grid</classname> y la <classname>Window</classname>. Si se propaga, el texto que esté escribiendo aparecerá en el <classname>Label</classname> arriba del <classname>Entry</classname>.Siempre que presiona o suelta una tecla, se emite un evento. Puede conectar un manejador de señales para manejar tales eventos.¿Por qué usar <application>gtkmm</application> en vez de GTK+?Referencia de widgetsWidget::on_expose_event() se reemplazó por Widget::on_draw(), que asume que cairomm se usa para dibujar, a través del <classname>Cairo::Context</classname> provisto y no requiere que llame a <methodname>Cairo::Context::clip()</methodname>.WidgetsWidgets sin X-WindowsWidgets y ChildAnchorsLos widgets se ordenan dentro de widgets contenedores como marcos y cuardenos de notas, en una jerarquía de widgets dentro de widgets. Algunos de estos widgets contenedores, como <classname>Gtk::Grid</classname> no son visibles: sólo existen para ordenar otros widgets. Aquí hay un código de ejemplo que añade dos widgets <classname>Gtk::Button</classname> a un widget contenedor <classname>Gtk::Box</classname>: <placeholder-1/> y aquí se muestra cómo agregar el <classname>Gtk::Box</classname>, conteniendo esos botones, a un <classname>Gtk::Frame</classname>, que tiene un cuadro y título visibles: <placeholder-2/>Con Cairo, la misma función se usa para dibujar arcos, círculos, o elipses: <methodname>Cairo::Context::arc()</methodname>. Esta función toma cinco argumentos. Los dos primeros son las coordenadas del punto central del arco, el tercer argumento es el radio del arco, y los últimos dos argumentos definen el ángulo de inicio y fin del arco. Todos los ángulos se definen en radianes, por lo que dibujar un círculo es lo mismo que dibujar un arco de 0 a 2 * M_PI radianes. Un ángulo de 0 está en la dirección del eje positivo de X (en espacio de usuario). Un ángulo de M_PI/2 radianes (90 grados) está en la dirección del eje positivo de Y (en espacio de usuario). Los ángulos se incrementan en la dirección del eje positivo de X hacia el eje positivo de Y, por lo que con la matriz de transformación predeterminada, los ángulos incrementan en la dirección de las agujas del reloj (recuerde que el eje positivo de Y apunta hacia abajo).Trabajar con el código fuente de gtkmmEnvolver los tipos de retorno de <classname>GList*</classname> y <classname>GSList*</classname>: debe descubrir si el llamador debe liberar la lista y si debe liberar sus elementos, también mediante la lectura de la documentación de la función de C. Con esta información puede elegir la posesión (ninguna, superficial o profunda) para la regla de conversión m4, la que probablemente deba poner directamente en el archivo .hg porque la posesión depende de la función en lugar del tipo. Por ejemplo: <placeholder-1/>Envolver bibliotecas C con gmmprocEscribir manejadores de señalesEscribir los .defs de las «vfuncs»Señales de eventos de XLos eventos de X se describen con mayor detalle en la sección <link linkend="sec-xeventsignals">Señales de eventos de X</link> en el apéndice.Los eventos de X difieren un poco de otras señales. Estas diferencias se describen en la sección <link linkend="sec-xeventsignals">Señales de eventos de X</link> en el apéndice. Aquí se usarán los eventos del teclado para mostrar cómo pueden usarse en un programa los eventos de X.Sí, es correcto: una ventana sólo puede contener un widget. Entonces, ¿cómo puede usar una ventana para algo útil? Poniendo un contenedor de múltiples hijos en la ventana. Los widgets contenedores más útiles son <classname>Gtk::Grid</classname> y <classname>Gtk::Box</classname>.Es probable que encuentre algunos problemas en la biblioteca que está envolviendo, particularmente si es un proyecto nuevo. Aquí hay algunos problemas comunes, con soluciones.No se le garantiza obtener el <literal>Gtk::SizeRequestMode</literal> que pida. Por lo tanto, los cuatro métodos <methodname>get_preferred_xxx_vfunc()</methodname> deben devolver valores razonables.Puede ajustar la posición del divisor usando el método <methodname>set_position()</methodname>, y probablemente lo necesite.También puede convertir a un tipo derivado, pero la sintaxis es un poco diferente que con un puntero normal.También puede conectarle señales a un <classname>CellRenderer</classname> para detectar las acciones del usuario. Por ejemplo:También puede especificar un manejador de señales cuando llame a <methodname>ActionGroup::add()</methodname>. Se llamará a este manejador de señales cuando se active la acción a través de un elemento del menú o un botón de la barra de herramientas.También puede usar <methodname>get_tag_table()</methodname> para obtener, y tal vez modificar, la <classname>TagTable</classname> predeterminada del <classname>TextBuffer</classname> en lugar de crear una explícitamente.Puede aplicar más de una <classname>Tag</classname> al mismo texto, usando <methodname>apply_tag()</methodname> más de una vez, o usando <methodname>insert_with_tags()</methodname>. Las <classname>Tag</classname> podrían especificar valores diferentes para las mismas propiedades, pero puede resolver estos conflictos usando <methodname>Tag::set_priority()</methodname>.Puede construir varios módulos estableciendo la variable <varname>modules</varname> a un metapaquete, como por ejemplo <literal>meta-gnome-core</literal>, o listando más de un nombre de módulo. La variable <varname>modules</varname> especifica qué módulos se construirán cuando no especifique explícitamente nada en la línea de comandos. Puede construir un conjunto de módulos diferente más tarde especificándolo en la línea de comandos (por ejemplo, <command>jhbuild build gtkmm</command>).Puede convertir <classname>RefPtr</classname> a tipos base, al igual que a los punteros normales.Puede copiar <classname>RefPtr</classname> como punteros normales. Pero, a diferencia de los punteros normales, no necesita preocuparse por la eliminación de la instancia subyacente.Puede crear un <classname>RecentManager</classname> nuevo, pero es muy probable que prefiera usar el predeterminado. Puede obtener una referencia del <classname>RecentManager</classname> predeterminado con <methodname>get_default()</methodname>.Puede desreferenciar un puntero inteligente con el operador -&gt; para llamar a los métodos de la instancia subyacente, al igual que un puntero normal.Puede desreferenciar al iterador para obtener la fila:Puede dibujar formas muy sofisticadas usando Cairo, pero los métodos para hacerlo son bastante básicos. Cairo proporciona métodos para dibujar líneas rectas, curvas, y arcos (incluyendo círculos). Estas formas básicas pueden combinarse para crear formas más complejas y caminos que pueden llenarse con colores sólidos, gradientes, patrones, y otras cosas. Además, Cairo puede realizar transformaciones complejas, componer imágenes, y generar texto con «antialiasing».Puede empotrar widgets, como <classname>Gtk::Button</classname> en el texto. Cada widget hijo necesitará un <classname>ChildAnchor</classname>. Los «ChildAnchor» están asociados a los <classname>iterators</classname>. Por ejemplo, para crear un «ChildAnchor» en una posición particular, use <methodname>Gtk::TextBuffer::create_child_anchor()</methodname>:Puede modificar la política de actualización usando el método <methodname>set_update_policy()</methodname>, especificando <literal>Gtk::UPDATE_ALWAYS</literal> o <literal>Gtk::UPDATE_IF_VALID</literal>. <literal>Gtk::UPDATE_ALWAYS</literal> hace que el <classname>SpinButton</classname> ignore los errores encontrados cuando se convierte el texto en el cuadro de entrada a un valor numérico. Esta opción, por lo tanto, también le permite al <classname>SpinButton</classname> aceptar valores no numéricos. Puede forzar a una actualización inmediata usando el método <methodname>update()</methodname>.Puede establecer las propiedades <emphasis>margin</emphasis> y <emphasis>expand</emphasis> de los <classname>Widget</classname> hijos para controlar su espaciado y comportamiento cuando se redimensiona la cuadrícula.Puede establecer el valor del «spinbutton» usando el método <methodname>set_value()</methodname>, y obtenerlo con <methodname>get_value()</methodname>.Puede especificar un <classname>Gtk::TreeModel</classname> cuando construye la <classname>Gtk::TreeView</classname>, o puede usar el método <methodname>set_model()</methodname>, así:Puede especificar un nombre para la clase <classname>Tag</classname> cuando use el método <methodname>create()</methodname>, pero no es necesario.Puede detener el método del período de espera mediante la devolución de <literal>false</literal> desde su manejador de señales. Por lo tanto, si quiere que su método se llame repetidamente, debe devolver <literal>true</literal>.Entonces, puede conectar la señal «edited» apropiada. Por ejemplo, conectarlo a <methodname>Gtk::CellRendererText::signal_edited()</methodname>, o a <methodname>Gtk::CellRendererToggle::signal_toggled()</methodname>. Si la columna contiene más de un <classname>CellRenderer</classname>, entonces tendrá que usar <methodname>Gtk::TreeView::get_column()</methodname> y luego llamar a <methodname>get_cell_renderers()</methodname> en esa columna de la vista.Puede entonces conectar a la señal usando la misma sintaxis que usaba cuando conectaba a señales de <application>gtkmm</application>. Por ejemplo, <placeholder-1/>Puede entonces usar el método <methodname>get_iter()</methodname> más tarde para crear un iterador para la posición nueva de la <classname>Mark</classname>.Puede usar <application>Glade</application> para distribuir sus propios widgets personalizados derivados de las clases de widgets de <application>gtkmm</application>. Esto mantiene su código organizado y encapsulado. Por supuesto, no verá la apariencia exacta ni las propiedades de su widget derivado en <application>Glade</application>, pero puede especificar su ubicación, widgets hijos y las propiedades de su clase base de <application>gtkmm</application>.Puede usar las API de C que no tengan todavía interfaces C++ convenientes. Generalmente no es un problema usar las API de C desde C++, y <application>gtkmm</application> le ayuda proporcionándole acceso al objeto C subyacente y una forma fácil de crear un objeto C++ envoltorio desde un objeto C, si la API de C también está basada en el sistema GObject.Puede usar el método <methodname>append_column()</methodname> para decirle a la vista que debe mostrar ciertas columnas del modelo, en cierto orden, con un cierto título de columna.Puede usar la sobrecarga <methodname>operator[]</methodname> para obtener los datos de una columna particular en una fila, especificando la <classname>TreeModelColumn</classname> que se usó para crear el modelo.Puede usar la sobrecarga de <methodname>operator[]</methodname> para establecer los datos de una columna particular en la fila, especificando la <classname>TreeModelColumn</classname> que se usó para crear el modelo.Puede usar el método <methodname>toggled()</methodname> para conmutar el botón, en vez de forzarlo a estar arriba o abajo: esto conmuta el estado del botón, y hace que se emita la señal <literal>toggled</literal>.<classname>Gtk::Clipboard</classname> es un «singleton». Puede obtener la instancia predeterminada del portapapeles con <methodname>Gtk::Clipboard::get()</methodname>. Esta es, probablemente, el único portapapeles que necesitará.También podría simplemente declarar esa señal como una variable miembro pública, pero algunas personas lo encuentran desastroso y prefieren hacerla disponible mediante un método de acceso, así: <placeholder-1/>Puede entonces encapsular la manipulación de los widgets hijos en el constructor de la clase derivada, tal vez usando <methodname>get_widget()</methodname> o <methodname>get_widget_derived()</methodname> nuevamente. Por ejemplo, <placeholder-1/>No necesita llamar siempre al método del padre; hay veces en las que no querrá hacerlo. Tenga en cuenta que se ha llamado al método padre <emphasis>después</emphasis> de escribir «Hello World», pero se podría haber llamado antes. En este ejemplo simple, no importa mucho, pero hay veces en las que lo hará. Con señales, no es tan fácil cambiar detalles como este, y puede hacer algo aquí que no puede con manejadores de señales conectados: puede llamar al método padre en la <emphasis>mitad</emphasis> de su código personalizado.No hay manera de obtener un <classname>Gdk::Pixbuf</classname> simple. En este ejemplo, <varname>pixbuf</varname> es un puntero inteligente, por lo que puede hacer esto, de manera muy similar a un puntero normal: <placeholder-1/>Puede añadir una pestaña personalizada al diálogo de impresión: <placeholder-1/>Puede preguntarse cómo hacer que <application>gtkmm</application> haga trabajo útil mientras está en espera. Afortunadamente, cuenta con varias opciones. Usando los siguientes métodos puede crear un método de tiempo de espera que se llamará cada una cierta cantidad de milisegundos.También podrá derivar clases que no sean widgets de Gtk::Object para que puedan usarse sin <classname>Glib::RefPtr</classname>. Por ejemplo, podrían instanciarse con <function>Gtk::manage()</function> o en la pila como una variable miembro. Esto es cómodo, pero sólo debe usarlo cuando esté seguro de que no se necesita conteo de referencias real. Se considera de utilidad para los widgets.Puede sorprenderle aprender que <application>gtkmm</application> no utiliza <classname>std::string</classname> en sus interfaces. En cambio, usa <classname>Glib::ustring</classname>, que es tan similar y discreto que en realidad puede pretender que cada <classname>Glib::ustring</classname> es un <classname>std::string</classname> e ignorar el resto de esta sección. Pero siga leyendo si quiere aplicar otros lenguajes además del inglés en su aplicación.Tal vez necesite reaccionar a cada cambio de la selección en el «ComboBox», por ejemplo, para actualizar otros widgets. Para hacer esto, debe manejar la señal <literal>changed</literal>. Por ejemplo:Puede no anticipar la necesidad de soportar lenguajes adicionales, pero nunca puede excluirla. Y es más fácil desarrollar la aplicación apropiadamente en primer lugar en vez de adecuarla después.Entonces podrá manejar la señal <literal>clicked</literal> del <classname>ToolButton</classname>. Alternativamente puede permitir que se arrastre el elemento a otro widget, llamando a <methodname>Gtk::ToolPalette::add_drag_dest()</methodname> y después usando <methodname>Gtk::ToolPalette::get_drag_item()</methodname> en el manejador de la señal <literal>drag_data_received</literal> del otro widget.Puede querer asociar datos adicionales a cada fila. Si es así, sólo añádalos como una columa del modelo, pero no se los añada a la vista.Tal vez quiera que se le notifique cuando el usuario escribe en un widget de entrada de texto. <classname>Gtk::Entry</classname> proporciona dos señales, <literal>activate</literal> y <literal>changed</literal> para este propósito. <literal>activate</literal> se emite cuando el usuario pulsa la tecla Intro en un widget de entrada de texto; <literal>changed</literal> se emite cuando el texto en el widget cambia. Puede usarlas, por ejemplo, para validar o filtrar el texto que el usuario introduce. Mover el foco del teclado a otro widget también podría señalar que el usuario ha terminado de introducir texto. La señal <literal>focus_out_event</literal> que <classname>Gtk::Entry</classname> hereda de <classname>Gtk::Widget</classname> puede notificarle cuando esto sucede. La sección <link linkend="sec-comboboxentry">«ComboBox» con una entrada</link> contiene programas de ejemplo que usan estas señales.Tal vez quiera incluir archivos de código fuente adicionales que <command>gmmproc</command> no generará desde archivos <filename>.hg</filename> y <filename>.ccg</filename>. Puede simplemente ponerlos en su carpeta <filename>libsomething/libsomethingmm</filename> y mencionarlos en el <filename>Makefile.am</filename> en las variables <varname>files_extra_h</varname> y <varname>files_extra_cc</varname>.Tal vez quiera reutilizar documentación que exista para la biblioteca de C que está envolviendo. Las bibliotecas GTK de C típicamente usan gtk-doc y por lo tanto tienen comentarios en el código fuente en formato de gtk-doc y alguna documentación adicional en archivos .sgml y .xml. El script «docextract_to_xml.py», de la carpeta <filename>tools/defs_gen</filename> de glibmm, puede leer estos archivos y crear un archivo .xml que <command>gmmproc</command> puede usar para generar comentarios de doxygen. <command>gmmproc</command> incluso intentará transformar la documentación para hacerla más apropiada para una API de C++.Debe llamar al constructor de la clase base en la lista de inicialización, proporcionándole el puntero de C. Por ejemplo, <placeholder-1/>Debe editar el código fuente de su herramienta <filename>generate_extra_defs</filename> para generar los <filename>.defs</filename> para los tipos GObject de C que desea envolver. En el árbol de fuentes esqueleto, el archivo de fuentes se llama <filename>codegen/extradefs/generate_extra_defs_skeleton.cc</filename>. Si no lo ha hecho todavía, debe renombrar el archivo, con el nombre de base de su enlace nuevo sustituyendo a la marca de posición <varname>skeleton</varname>. El archivo <filename>codegen/Makefile.am</filename> también debe mencionar el nombre del archivo de fuentes nuevo.Debe establecer el parámetro opcional <literal>after = false</literal> en la llamada a <literal>signal_command_line().connect()</literal>, porque su manejador de señales debe llamarse antes que el manejador predeterminado. También debe llamar a <methodname>Gio::Application::activate()</methodname> en este, a menos que quiere que su aplicación se cierre sin mostrar su ventana principal. (<classname>Gio::Application</classname> es una clase base de <classname>Gtk::Application</classname>).Debe especificar las características del <classname>Alignment</classname> al constructor, o al método <methodname>set()</methodname>. En particular, no notará ningún efecto a menos que especifique un número distinto a 1.0 para los parámetros <literal>xscale</literal> e <literal>yscale</literal>, porque 1.0 simplemente significa que el widget se expandirá hasta cubrir todo el espacio disponible.Nunca sabe cuánto espacio ocupará una cadena en la pantalla cuando se haya traducido. Bien podría duplicar el tamaño de la cadena original en inglés. Afortunadamente, la mayoría de los widgets de <application>gtkmm</application> se expandirán en tiempo de ejecución al tamaño requerido.Probablemente nunca necesite adjuntarle un manejador a esta señal, a menos que esté escribiendo un nuevo tipo de widget de rango.Evite la aritmética de punteros al estilo C, y funciones como strlen(). En UTF-8, cada carácter podría necesitar entre 1 y 6 bytes, por lo que no es posible asumir que el próximo byte es otro carácter. <classname>Glib::ustring</classname> se ocupa de estos detalles, por lo que puede usar métodos como Glib::ustring::substr() y seguir pensando en términos de caracteres en vez de bytes.Debe evitar abreviaciones crípticas, lenguaje vulgar o técnico. Estos son generalmente difíciles de traducir e incluso les pueden resultar difíciles de entender a los hablantes nativos. Por ejemplo, es preferible «application» antes que «app».Debe evitar incluir la cabecera de C desde su cabecera de C++, para evitar contaminar el espacio de nombres global, y para evitar exportar API pública innecesaria. Pero necesitará incluir las cabeceras de C desde su archivo .ccg.Debe tener mucho cuidado al instalar en prefijos estándar del sistema, como <filename>/usr</filename>. Las distribuciones de Linux instalan paquetes de software en <filename>/usr</filename>, por lo que instalar un paquete de fuentes en este prefijo puede corromper o crear un conflicto con el software instalado usando el sistema de gestión de paquetes de su distribución. De manera ideal, debería usar un prefijo separado para todo el software que instale desde las fuentes.No declare estos tipos usted mismo. Utilice, en cambio, el contenedor estándar C++ que prefiera. glibmm hará la conversión. Aquí hay algunos de estos tipos intermedios: <placeholder-1/>Debe guardar la <classname>Gtk::PageSetup</classname> elegida para poder usarla luego si se vuelve a mostrar el diálogo de configuración de la página.Entonces, convierta ese <classname>Gtk::CellRenderer*</classname> al <classname>CellRenderer</classname> específico que espera, para que pueda usar la API específica.Especifique el <classname>ColumnRecord</classname> cuando cree el modelo, así:Aún así necesitará código C++ para ocuparse de los cambios en la interfaz de usuario desencadenados por las acciones del usuario, pero usar <application>Gtk::Builder</application> para la distribución de los widgets le permite enfocarse en la implementación de esa funcionalidad.Típicamente usará esta macro cuando la clase ya derive de Gtk::Object. Por ejemplo, la usará cuando envuelva un widget de GTK+, porque Gtk::Widget deriva de Gtk::Object.Probablemente ya haya notado que las ventanas de <application>gtkmm</application> parecen «elásticas»: normalmente pueden estirarse de muchas maneras diferentes. Esto es así por el sistema de <emphasis>empaquetado de widgets</emphasis>.Para que su aplicación no necesite esperar a operaciones de portapapeles, particularmente en el tiempo en el que el usuario elige «copiar» y luego «pegar», la mayoría de los métodos de <classname>Gtk::Clipboard</classname> toman <classname>sigc::slot</classname> que especifican métodos de retorno de llamada. Cuando <classname>Gtk::Clipboard</classname> esté listo, llamará a estos métodos, proporcionándoles los datos o bien pidiéndolos.Su retorno de llamada proporcionará entonces los datos almacenados cuando el usuario elija pegarlos. Por ejemplo:Su clase derivada debe tener un constructor que tome un puntero al tipo C subyacente, y a la instancia <classname>Gtk::Builder</classname>. Todas las clases relevantes de <application>gtkmm</application> crean alias de sus tipos C subyacentes como <classname>BaseObjectType</classname> (<classname>Gtk::Dialog</classname> define un alias de <classname>BaseObjectType</classname> como <type>GtkDialog</type>, por ejemplo).Conocer C++ le ayudará con <application>gtkmm</application> como lo haría con cualquier otra biblioteca. A menos que se indique lo contrario, el comportamiento de las clases de <application>gtkmm</application> será como el de cualquier otra clase C++, de manera que podrá utilizar sus actuales técnicas de C++ con las clases de <application>gtkmm</application>.Su implementación del método <methodname>child_type_vfunc()</methodname> debe reportar el tipo de widget que puede añadírsele a su contenedor, si todavía no está lleno. Esto es generalmente <methodname>Gtk::Widget::get_type()</methodname> para indicar que el contenedor puede contener cualquier clase derivada de <classname>Gtk::Widget</classname>. Si el contenedor no puede contener más widgets, entonces este método debe devolver <literal>G_TYPE_NONE</literal>.Su biblioteca debe inicializarse antes de que pueda usarla, para registrar los tipos nuevos que hace disponibles. Además, la biblioteca de C que está envolviendo podría tener su propia función de inicialización a la que debe llamar. Puede hacerlo en una función <function>init()</function> que puede poner en archivos <filename>init.h</filename> e <filename>init.cc</filename> programados a mano. Esta función debe inicializar sus dependencias (como la función de C, y <application>gtkmm</application>) y llamar a su función <function>wrap_init()</function> generada. Por ejemplo: <placeholder-1/>_CLASS_BOXEDTYPE_CLASS_BOXEDTYPE( C++ class, C class, new function, copy function, free function )_CLASS_BOXEDTYPE_STATIC_CLASS_BOXEDTYPE_STATIC( C++ class, C class )_CLASS_GENERIC_CLASS_GENERIC( C++ class, C class )_CLASS_GOBJECT_CLASS_GOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )_CLASS_GTKOBJECT_CLASS_GTKOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )_CLASS_GTKOBJECT()_CLASS_INTERFACE_CLASS_INTERFACE( C++ class, C class, C casting macro, C interface struct, Base C++ class (optional), Base C class (optional) )_CLASS_OPAQUE_COPYABLE_CLASS_OPAQUE_COPYABLE( C++ class, C class, new function, copy function, free function )_CLASS_OPAQUE_REFCOUNTED_CLASS_OPAQUE_REFCOUNTED( C++ class, C class, new function, ref function, unref function )_CTOR_DEFAULT_DEFS()_IGNORE / _IGNORE_SIGNAL_IGNORE(C function name 1, C function name2, etc)_IGNORE_SIGNAL(C signal name 1, C signal name2, etc)_IMPLEMENTS_INTERFACE_IMPLEMENTS_INTERFACE()_IMPLEMENTS_INTERFACE(C++ interface name)_MEMBER_GET / _MEMBER_SET_MEMBER_GET(C++ name, C name, C++ type, C type)_MEMBER_GET(x, x, int, int)_MEMBER_GET_GOBJECT / _MEMBER_SET_GOBJECT_MEMBER_GET_GOBJECT(C++ name, C name, C++ type, C type)_MEMBER_GET_PTR / _MEMBER_SET_PTR_MEMBER_GET_PTR(C++ name, C name, C++ type, C type)_MEMBER_SET(C++ name, C name, C++ type, C type)_MEMBER_SET_GOBJECT(C++ name, C name, C++ type, C type)_MEMBER_SET_PTR(C++ name, C name, C++ type, C type)_PINCLUDE()_WRAP_CTOR_WRAP_ENUM_WRAP_ENUM_DOCS_ONLY_WRAP_GERROR_WRAP_METHOD_WRAP_METHOD( C++ method signature, C function name)_WRAP_METHOD_DOCS_ONLY_WRAP_METHOD_DOCS_ONLY(C function name)_WRAP_PROPERTY_WRAP_PROPERTY(C property name, C++ type)_WRAP_SIGNAL_WRAP_SIGNAL( C++ signal handler signature, C signal name)_WRAP_VFUNC_WRAP_VFUNC( C++ method signature, C function name)adj-&gt;signal_value_changed().connect(sigc::bind&lt;MyPicture*&gt;(sigc::mem_fun(*this,
    &amp;cb_rotate_picture), picture));adjustment-&gt;signal_changed();y conectarlo al ajuste del widget de escala así:Y luegoatkmmbinding_namebindtextdomain(GETTEXT_PACKAGE, PROGRAMNAME_LOCALEDIR);
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
textdomain(GETTEXT_PACKAGE);boolbool DemoWindow::select_function(
    const Glib::RefPtr&lt;Gtk::TreeModel&gt;&amp; model,
    const Gtk::TreeModel::Path&amp; path, bool)
{
  const Gtk::TreeModel::iterator iter = model-&gt;get_iter(path);
  return iter-&gt;children().empty(); // only allow leaf nodes to be selected
}bool ExampleWindow::on_button_press_event(GdkEventButton* event)
{
  if( (event-&gt;type == GDK_BUTTON_PRESS) &amp;&amp;
      (event-&gt;button == 3) )
  {
    m_Menu_Popup-&gt;popup(event-&gt;button, event-&gt;time);
    return true; //It has been handled.
  }
  else
    return false;
}bool MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  Glib::RefPtr&lt;Gdk::Pixbuf&gt; image = Gdk::Pixbuf::create_from_file("myimage.png");
  // Draw the image at 110, 90, except for the outermost 10 pixels.
  Gdk::Cairo::set_source_pixbuf(cr, image, 100, 80);
  cr-&gt;rectangle(110, 90, image-&gt;get_width()-20, image-&gt;get_height()-20);
  cr-&gt;fill();
  return true;
}ejemplo de botonescairocairommcell.property_editable() = true;class HelloWorld : public Gtk::Window
{

public:
  HelloWorld();
  virtual ~HelloWorld();

protected:
  //Signal handlers:
  virtual void on_button_clicked();

  //Member widgets:
  Gtk::Button m_button;
};class ModelColumns : public Gtk::TreeModelColumnRecord
{
public:

  ModelColumns()
    { add(m_col_text); add(m_col_number); }

  Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_text;
  Gtk::TreeModelColumn&lt;int&gt; m_col_number;
};

ModelColumns m_Columns;class RadioButtons : public Gtk::Window
{
public:
    RadioButtons();

protected:
    Gtk::RadioButton m_rb1, m_rb2, m_rb3;
};

RadioButtons::RadioButtons()
  : m_rb1("button1"),
    m_rb2("button2"),
    m_rb3("button3")
{
    Gtk::RadioButton::Group group = m_rb1.get_group();
    m_rb2.set_group(group);
    m_rb3.set_group(group);
}class RadioButtons : public Gtk::Window
{
public:
    RadioButtons();
};

RadioButtons::RadioButtons()
{
    Gtk::RadioButton::Group group;
    Gtk::RadioButton *m_rb1 = Gtk::manage(
      new Gtk::RadioButton(group,"button1"));
    Gtk::RadioButton *m_rb2 = manage(
      new Gtk::RadioButton(group,"button2"));
      Gtk::RadioButton *m_rb3 = manage(
        new Gtk::RadioButton(group,"button3"));
}clickedconfigure.acconstversioncontext-&gt;save();
context-&gt;translate(x, y);
context-&gt;scale(width / 2.0, height / 2.0);
context-&gt;arc(0.0, 0.0, 1.0, 0.0, 2 * M_PI);
context-&gt;restore();custom_c_callbackcustom_default_handlercustom_vfunccustom_vfunc_callbackdeprecateddisplay_message("Getting ready for i18n.");display_message(_("Getting ready for i18n."));dobleenterenumserrthrowevent_box.add(child_widget);flags: se usan sólo para arrastrar y soltar, y especifican si los datos pueden arrastrarse a otros widgets y aplicaciones, o sólo a los mismos.funcionesg++ simple.cc -o simple `pkg-config gtkmm-3.0 --cflags --libs`gbooleangchar*gdk-pixbufgdoublemanual de gettextgintglibglibmmProcesado de parámetros de gmmprocgnomemm_hellogtk.defsgtk_enums.defsgtk_methods.defsgtk_signals.defsgtk_vfuncs.defsgtkmmgtkmm_helloguintgunicharifdefinfo: un identificador, que se enviará a sus señales para comunicarle qué «TargetEntry» se usó.intint cols_count = m_TreeView.append_column_editable("Alex", m_columns.alex);
Gtk::TreeViewColumn* pColumn = m_TreeView.get_column(cols_count-1);
if(pColumn)
{
  Gtk::CellRendererToggle* pRenderer =
    static_cast&lt;Gtk::CellRendererToggle*&gt;(pColumn-&gt;get_first_cell());
  pColumn-&gt;add_attribute(pRenderer-&gt;property_visible(), m_columns.visible);
  pColumn-&gt;add_attribute(pRenderer-&gt;property_activatable(), m_columns.world);int main(int argc, char** argv)
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  HelloWorld helloworld;
  return app-&gt;run(helloworld);
}intltool-update --potleavelib_LTLIBRARIESlibsigc++ 2.0Conversiones m4Inicializaciones de m4m_TextView.add_child_at_anchor(m_Button, refAnchor);m_TreeView.append_column("Messages", m_Columns.m_col_text);m_TreeView.set_model(m_refListStore);m_box.pack_start(m_Button1);
m_box.pack_start(m_Button2);m_button1.signal_clicked().connect( sigc::mem_fun(*this,
  &amp;HelloWorld::on_button_clicked) );m_combo.set_entry_text_column(m_columns.m_col_name);m_combo.signal_changed().connect( sigc::mem_fun(*this,
      &amp;ExampleWindow::on_combo_changed) );m_frame.add(m_box);m_rb2.set_group(m_rb1.get_group()); //doesn't workm_refActionGroup = Gtk::ActionGroup::create();

m_refActionGroup-&gt;add( Gtk::Action::create("MenuFile", "_File") );
m_refActionGroup-&gt;add( Gtk::Action::create("New", "_New"),
  sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_new) );
m_refActionGroup-&gt;add( Gtk::Action::create("ExportData", "Export Data"),
  sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_open) );
m_refActionGroup-&gt;add( Gtk::Action::create("Quit", "_Quit"),
  sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_quit) );m_refTreeSelection-&gt;set_select_function( sigc::mem_fun(*this,
    &amp;DemoWindow::select_function) );modules = [ 'gtkmm' ]moduleset = 'gnome-suites-core-deps-3.12'no_default_handlerno_slot_copyobjetos (GObjects, widgets, interfaces, tipos en caja y estructuras planas)opangommpkg-configpressedpropiedadesrefBuffer-&gt;apply_tag(refTagMatch, iterRangeStart, iterRangeStop);refBuffer-&gt;insert_with_tag(iter, "Some text", refTagMatch);refClipboard-&gt;request_contents("example_custom_target",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_received) );refClipboard-&gt;request_targets( sigc::mem_fun(*this,
    &amp;ExampleWindow::on_clipboard_received_targets) );refTreeSelection-&gt;selected_foreach_iter(
    sigc::mem_fun(*this, &amp;TheClass::selected_row_callback) );

void TheClass::selected_row_callback(
    const Gtk::TreeModel::iterator&amp; iter)
{
  TreeModel::Row row = *iter;
  //Do something with the row.
}refTreeSelection-&gt;set_mode(Gtk::SELECTION_MULTIPLE);refTreeSelection-&gt;signal_changed().connect(
    sigc::mem_fun(*this, &amp;Example_IconTheme::on_selection_changed)
);refreturnrefreturn_ctypereleasedreturn app-&gt;run(window);row[m_Columns.m_col_text] = "sometext";señalesslot_callbackslot_namesrc/main.cc
src/other.ccstd::cout &lt;&lt; Glib::ustring::compose(
             _("Current amount: %1 Future: %2"), amount, future) &lt;&lt; std::endl;

label.set_text(Glib::ustring::compose(_("Really delete %1 now?"), filename));std::cout &lt;&lt; _("Current amount: ") &lt;&lt; amount
          &lt;&lt; _(" Future: ") &lt;&lt; future &lt;&lt; std::endl;

label.set_text(_("Really delete ") + filename + _(" now?"));std::ostringstream output;
output.imbue(std::locale("")); // use the user's locale for this stream
output &lt;&lt; percentage &lt;&lt; " % done";
label-&gt;set_text(Glib::locale_to_utf8(output.str()));std::stringstd::string utiliza 8 bits por carácter, pero 8 bits no son suficientes para codificar lenguajes como árabe, chino y japonés. A pesar de que las codificaciones de estos lenguajes ahora las ha especificado el Consorcio Unicode, los lenguajes C y C++ todavía no proporcionan ningún soporte Unicode estándar. GTK+ y GNOME eligen implementar Unicode usando UTF-8, y eso es lo que está envuelto en Glib::ustring. Proporciona casi exactamente la misma interfaz que std::string, además de conversiones automáticas desde y hacia std::string.std::vector&lt; Glib::RefPtr&lt;Gtk::RecentInfo&gt; &gt; info_list = recent_manager-&gt;get_items();target: un nombre, como por ejemplo «STRING»Nicolás Satragno <nsatragno@gmail.com>, 2012
José Zambrano <jozaol@gmail.com>, 2011
Daniel Mustieles <daniel.mustieles@gmail.com>, 2011
Jorge González <jorgegonz@svn.gnome.org>, 2010typedef Gtk::TreeModel::Children type_children; //minimise code length.
type_children children = refModel-&gt;children();
for(type_children::iterator iter = children.begin();
    iter != children.end(); ++iter)
{
  Gtk::TreeModel::Row row = *iter;
  //Do something with the row - see above for set/get.
}«vfuncs»«vfuncs» (campos miembro de punteros de funciones en estructuras), escritas a mano.void ExampleWindow::on_button_delete()
{
  Glib::RefPtr&lt;Gtk::TreeSelection&gt; refTreeSelection =
      m_treeview.get_selection();
  if(refTreeSelection)
  {
    Gtk::TreeModel::iterator sorted_iter =
        m_refTreeSelection-&gt;get_selected();
    if(sorted_iter)
    {
      Gtk::TreeModel::iterator iter =
          m_refModelSort-&gt;convert_iter_to_child_iter(sorted_iter);
      m_refModel-&gt;erase(iter);
    }
  }
}void ExampleWindow::on_clipboard_get(
    Gtk::SelectionData&amp; selection_data, guint /* info */)
{
  const std::string target = selection_data.get_target();

  if(target == "example_custom_target")
    selection_data.set("example_custom_target", m_ClipboardStore);
}void ExampleWindow::on_clipboard_received(
    const Gtk::SelectionData&amp; selection_data)
{
  Glib::ustring clipboard_data = selection_data.get_data_as_string();
  //Do something with the pasted data.
}void ExampleWindow::on_clipboard_received_targets(
  const std::vector&lt;Glib::ustring&gt;&amp; targets)
{
  const bool bPasteIsPossible =
    std::find(targets.begin(), targets.end(),
      example_target_custom) != targets.end();

  // Enable/Disable the Paste button appropriately:
  m_Button_Paste.set_sensitive(bPasteIsPossible);
}void cb_rotate_picture (MyPicture* picture)
{
  picture-&gt;set_rotation(adj-&gt;get_value());
...void doSomething(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; context, int x)
{
    context-&gt;save();
    // change graphics state
    // perform drawing operations
    context-&gt;restore();
}void drag_dest_set(const std::vector&lt;Gtk::TargetEntry&gt;&amp; targets,
    Gtk::DestDefaults flags, Gdk::DragAction actions);void drag_source_set(const std::vector&lt;Gtk::TargetEntry&gt;&amp; targets,
      Gdk::ModifierType start_button_mask, Gdk::DragAction actions);void pack_start(Gtk::Widget&amp; child,
                Gtk::PackOptions options = Gtk::PACK_EXPAND_WIDGET,
                guint padding = 0);donde <parameter>condition</parameter> se especifica como se mencionó previamente. Como de costumbre, el «slot» se crea con <function>sigc::mem_fun()</function> (para un método miembro de un objeto), o <function>sigc::ptr_fun()</function> (para una función).wrap_init_flagsxgettext -a -o my-strings --omit-header *.cc *.h