File: es.mo

package info (click to toggle)
gtkmm-documentation 4.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 25,772 kB
  • sloc: cpp: 15,541; javascript: 1,208; makefile: 1,080; python: 401; xml: 106; perl: 67; sh: 8
file content (2148 lines) | stat: -rw-r--r-- 426,535 bytes parent folder | download
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
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
",)<Rm]mjmjnn+opqer>tA/uaquIuvv.{xz{t|>}7@X[7"VUBZ:YDٗOn2ٚEk2)RIaZachg̝:4oP#ܟTHUN[BIkA):Wd>G=Cj.8P:2(m(I?	TIeh_
HjagJ}Ȭ8`\sSXǯc joB|\d3Դsd46Ҽcw1na\7KPlpa5F85YnEH%h21XdSU)gFUe]x ''H)p#&'
:-h.1w`*TaJ/Gw-fF1,x ]'~%%re_:@O/%Uwp7
*nlCq)\2f&+=#[$^=4A=v8gBU9hj;'mco"A	d		,;
>h
D
L
H9DLH ]s~>O1
H

q*~/$*xOcx+$+PQ+35:p-}B/  !)!=!R!d!w!!b!\"c^"e"e(#c#]#aP$$`%e'&l&b&`]'_'i(k(k(_`)^)a*_*c*gE+b+c,_t,h,e=-e-_	._i.c.h-/d/d/i`0b0b-1a1f1bY2Y2f4i}4c4cK5b5g6yz6x6rm7q7|R8|8|L9|9|F:|:|@;|;|:<{<|3==2>~>3?~?2@@{9AA<BBBCCSDD~_EE^FF^GGdH~HxhI|Iz^JsJrMKyKs:LuLt$MM$NsN~OzOPyPwQsQ~Qy~R{RztS|S}lTxTwcUvUvRVVOW|W}SX|XNYU Z!vZ]ZjZ0a[[#\z\;,]ah]]^qD_`xaobwQeftg@iHjF
kTk`krk
zkk''lOl(lmm,m>mn}(nnnnGqr9t]uww8xzM|U}~;
)&PhLb
wNQڇ,	8&Bi;q$ҋ2t/lN
Ӑ
uz<ΔՔޔ-0ٕ{xїݗ(6_@v'Ҙ	)ț͛՛wğ
ʠa
=-ks̤]vtss

"0I]rʩ٩/!B&d{AHIѯ
. 0(Yb
IJֲ^GT
w,-
ҴeYFu{(ȶٷ+[=ǸR޸l1\NTJX`
 ͼ)$;:}3:4n6.
:EY
e/s7o*_#Cg 4C&Bje$8J4o"G$)Q>hr!djPcw-m!RM
FG,*S7H"%4=A1	bd#'b+HG	S]q,3	OouHZ
m
{
"*%(PyxF=:PMmS



wm$c'	O
j]xn&	DQN_r   tG!!"!!3"8"
@"K"Q"####=#[#S%\%
o%z%%%%a%$&=&E&T&]&o&&,')8'ob'
''
''
)))+)+,,	,,-$-!1-
S-a-s-	-b--]..
/000001	1!11111
1Q1Q35666b7k8)9(';IP<@@@@gAB
CCD2EFGGGNGHHH8JMM3OHO_OPQKRS=|TbUVYV_Y`|YNY,\?.]n]^_]`]aPb97cqd
jeuefg
h	hh
hhii#jjFkZk9jkplm	%mW/mnA%ogoWpmNrrsntuuvw	z{gW|{|B;~4~~	ak/N"cqՃ`Ά@_GT=	:DJً$C6z˒0
ؖj0]{juD%?נ/791mk٥c(Ui~έ	NCk^H_
dr9f~s[>:kR8n/D!7f2XU*7;<
d~m;a(9A[1Yk} $wEK;[B6w*Z?'i/Y^ro~		'i<N-@|
RJb3=/
%09Vopl-%,f
q'*yT{Y5		q
	S" v!~ys*eirLU~k0$\F !!b""#D$$%&(P)y*@*,.r/&012n3
55U566b7.8M9;;4;C;R;c;t;;
;;;;;;)<:<P<j<)<!<<
<
<<==)=@=O=\=h=A> >:>??'?g?@(B[B9C@CeDdkDDEpFqFTGjG
GH
IIJKKLLLLLL"M+M.M
NN/N8N%XN	~N>NNNNOOOOO4O;$P%`P1PaP4QeOQQiQ9RORgRzRFRR
RDR>!S`S7`TxT	UU'+USU'nUUU#U UUVVW4YD;YaYMY0[[{\b^r^
8_C_0&`W`]ajCbbb+cefef>4iAsiaiIjajj.lnpt
qq^sFtt{u@[vwx7.yfzz|}Z~وʼnDObvE2)(RRIZaJcg:x# TDHN[1BkЕA<)~W>G?=ŗjrݘ|P%:v((ښI?MT_NHagYJ8&`?sXcdȤjHKB|+\3Lsd_Ĭ4ǭ63c^w޲V1)aж\27ǷPcl!ayF28yYERHg%2yXSUY)F]d g')#&'%MBmN(d.1x1>NnR 7'X%%p=F0+_&/,Fs	L9E]!s^eL&%+Lx#$lBL4F8gDB9h)j'%mo(",>DLCHDLHk q>GOHc

=s

 5V1'-U,1T25w-&t/(Xi{	c]~dfAfd^tb(6a_fm(ca`\ j l(!l!`"_c"b"`&#d#h#cU$d$`%i%f%fP&`&`'dy'i'eH(e(j)c)c)bG*g*c+v+g-k|-d-dM.c.i/|/{/uy0t0d11d22d33d44d5~5c66h77o88t99~:;;<<"==8>>A??G@@RAA^B{B\C}CvZDuD|GEvEx;FwF,GGvCHH}<II|>JzJv6KK|/L~L}+MM)N{Nz&OyOyPPQQ(RR)SQT!eTdTkT0XUU#V{V69WapWWXgY[[]`ajb$dQeF$fkfwffff92glg2h4hCh_h|hiij8j@jMmnDYpq*s!sTt6wkBxyczg||%}7
B]"W zK҆	ކ*+S3,Љ߉QEɌَB;Qgmt|/KH	
ē-ٓɔߔΖ
$A^ k+?З&.
U`x
IT[ cC2L\wYrQ-9MM	L# 
7Eѧ_x0<Oi"Ȫ
*8Pp!&tӫEH>Ͱް"=Q gh|ò0#)"8[pb}4{zb8|(۸˹"
+(aT"ٺ\v_bֻ`9aX
*IN1U;a}/346-M{-2:9@n9(b!I2H|Jl}^`oG/w}JX=5sc,ig8eBViQ!:%1C4#3P@J@%8
^ql=
!
(h3j+Fbk!*gE5{|
t	2UVfD	
+
2
7N
n|#(76G/~
/5Sr@{$rizK"?b7@k3$I?jV  !m"K"#Dn${%/(*#*+N+[+v,",/,
,3,-'-A-M- .=. C.&d..000001'1a<1111
11122+233333
55585(78888!9	19&;9b9#t999k9":u:M;-
<;=Q=d={=%====>>>>
>o>L@FCCD3D3E6FFOIwVJN!NN
OO)MQ
wQQ1RST=V	FVPV\gVV$lWWLYR\O[\^^^`UabcRHdvefgff8i`ijlCmmnoaqqr?s&u	!v+vwwy	yyyzz&$zK{{{||8|o}W~
h~Ns~=jj[vƃ=DIDыhwEDhJ	ϒْij}]XrJWל!/
Q\SPFhZnwZzթڪrKu>Kwó0>
ͷ4ucit{s=X
Q?mF:<;9wu|2v~[pOF2?frgOA=r;b>%dBD;KWy7Ro[
,L Lcon3f8d1xTh?9fcSgy	%&p;KNZ$'	.		f
P# 2ET#k;{s$B,8[R' x o!h##$&)'};**+++'/"//$/0)0 012~3m-445u5q7ai99:y;6<I<j)>?n@	AAVB=CCD oEF\H(II}JL'NPPRSSUyVO"WrWXYn'[\\\\\\\]
/]=]O]\]t]])]]]])^!;^]^
o^
z^^^^^^^^^_ M`1n``?``{b(5d[^dd@EeeedeQfogpggThh
si~jjXkSlWmdm	nn2n?nUnqn"o+3o._ooooo%o	p>p#Kpopupp6qLqXqhq4q;q%q1raHr4rerEsi_ssss
tKtctetDqt>tt7ux-v	vv'vv'w+wFw#Ow swww|x9y
zUza+{M{|{}{>~b
0WN Y1)xak?M ]q>]z)GslBZc|.\><iF`UzF,&{$To~u4S@jA,/s.Xx7d^#L[W)o	 vkTa<
2*6cXR[D9("96|f8}Jmaq58<RJ;
`rdJ 3{G-IYG59vr@7Rx(0oSJ+u4,I6[$_
%%V5A9Q0B[
tI'KIh".pY8pGZ.=`06bPMQCVjD#yq.0S'Y{	i!ExWr,+Z4NFP5gmb"^k>O\KM'nl7;fS"]Ts6
;|(
q%}-u|P8
VXAi(:eBL	f!N_
4*m!$Hyh1v|OeiC9d3\M\^=fO~t`aly}TX>ke2*&@&j@##q&3>fh}n{,yzcRZBn?+g1n1?_!C# t/	gsP:UUUV2]X?=E@hD=N?r8Q	Kwgw
	(AH/mLV'Hljv'_pG~])2-Kpj`U3+zudJHbod<_e; I<t
B%T)DtlE=!v~hY+4W[C!C2Dks&
yE:m/}R:KN^QSx5*iLp{"ec1-n"/FO7zuE*;$Z-bQ3a:w~\wgAHFcP%07rWw^$boLMO

    ...
    button.signal_clicked().connect(sigc::ptr_fun(&amp;on_button_clicked));
    ...

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

# ./configure --prefix=/usr

#include &lt;glibmm_generate_extra_defs/generate_extra_defs.h&gt;
#include &lt;libsomething.h&gt;
#include &lt;iostream&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;
}

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

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

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;
}

int 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;gtkmm/widget.h&gt;
#include &lt;gtkmm/actionable.h&gt;
_DEFS(gtkmm,gtk)
_PINCLUDE(gtkmm/private/widget_p.h)

namespace Gtk
{

class Button
  : public Widget,
    public Actionable
{
  _CLASS_GTKOBJECT(Button, GtkButton, GTK_BUTTON, Gtk::Widget, GtkWidget)
  _IMPLEMENTS_INTERFACE(Actionable)
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

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

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

$ cd gtk/src
$ /usr/lib/glibmm-2.68/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

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;gresources&gt;
  &lt;gresource prefix="/toolbar"&gt;
    &lt;file preprocess="xml-stripblanks"&gt;toolbar.glade&lt;/file&gt;
    &lt;file&gt;rain.png&lt;/file&gt;
  &lt;/gresource&gt;
&lt;/gresources&gt;

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

// Connect the menu to the MenuButton m_gears, and bind the show-words setting
// to the win.show-words action and the "Words" menu item.
// (The connection between action and menu item is specified in gears_menu.ui.)
auto menu_builder = Gtk::Builder::create_from_resource("/org/gtkmm/exampleapp/gears_menu.ui");
auto menu = menu_builder-&gt;get_object&lt;Gio::MenuModel&gt;("menu");
m_gears-&gt;set_menu_model(menu);
add_action(m_settings-&gt;create_action("show-words"));

// Within a class that inherits from Gtk::Window and keeps m_refPageSetup
// and m_refSettings as members...
auto new_page_setup = Gtk::run_page_setup_dialog(*this, m_refPageSetup, m_refSettings);
m_refPageSetup = new_page_setup;

// _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...
auto op = PrintOperation::create();
// ...set up op...
op-&gt;run(Gtk::PrintOperation::Action::PREVIEW, *this);

// in class ExampleWindow's method...
auto 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);
  auto app = Gtk::Application::create("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();
  auto app = Gtk::Application::create("org.gtkmm.without_signal");
  return app-&gt;run();
}

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

DerivedButton::DerivedButton(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder)
: Glib::ObjectBase("MyButton"), // The GType name will be gtkmm__CustomObject_MyButton.
  Gtk::Button(cobject),
  prop_ustring(*this, "button-ustring"),
  prop_int(*this, "button-int", 10)
{
  // ....
}

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),
  //Get the Glade-instantiated Button, and connect a signal handler:
  m_pButton(m_builder-&gt;get_widget&lt;Gtk::Button&gt;("quit_button"))
{
  if(m_pButton)
  {
    m_pButton-&gt;signal_clicked().connect( sigc::mem_fun(*this, &amp;DerivedDialog::on_button_quit) );
  }
}

DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder, bool warning)
: Gtk::Dialog(cobject),
  m_builder(builder),
  m_pButton(m_builder-&gt;get_widget&lt;Gtk::Button&gt;("quit_button"))
{
  // ....
}

Glib::ustring ui_info =
  "&lt;interface&gt;"
  "  &lt;menu id='menu-examplepopup'&gt;"
  "    &lt;section&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;Edit&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;examplepopup.edit&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;Process&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;examplepopup.process&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;Remove&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;examplepopup.remove&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "    &lt;/section&gt;"
  "  &lt;/menu&gt;"
  "&lt;/interface&gt;";

m_refBuilder-&gt;add_from_string(ui_info);

auto gmenu = m_refBuilder-&gt;get_object&lt;Gio::Menu&gt;("menu-examplepopup");
m_pMenuPopup = std::make_unique&lt;Gtk::Menu&gt;(gmenu);

Glib::ustring ui_info =
  "&lt;interface&gt;"
  "  &lt;menu id='menubar'&gt;"
  "    &lt;submenu&gt;"
  "      &lt;attribute name='label' translatable='yes'&gt;_File&lt;/attribute&gt;"
  "      &lt;section&gt;"
  "        &lt;item&gt;"
  "          &lt;attribute name='label' translatable='yes'&gt;_New&lt;/attribute&gt;"
  "          &lt;attribute name='action'&gt;example.new&lt;/attribute&gt;"
  "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;n&lt;/attribute&gt;"
  "        &lt;/item&gt;"
  "      &lt;/section&gt;"
  "      &lt;section&gt;"
  "        &lt;item&gt;"
  "          &lt;attribute name='label' translatable='yes'&gt;_Quit&lt;/attribute&gt;"
  "          &lt;attribute name='action'&gt;example.quit&lt;/attribute&gt;"
  "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;q&lt;/attribute&gt;"
  "        &lt;/item&gt;"
  "      &lt;/section&gt;"
  "    &lt;/submenu&gt;"
  "    &lt;submenu&gt;"
  "      &lt;attribute name='label' translatable='yes'&gt;_Edit&lt;/attribute&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;_Copy&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;example.copy&lt;/attribute&gt;"
  "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;c&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;_Paste&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;example.paste&lt;/attribute&gt;"
  "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;v&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "    &lt;/submenu&gt;"
  "  &lt;/menu&gt;"
  "&lt;/interface&gt;";

m_refBuilder-&gt;add_from_string(ui_info);
m_refBuilder-&gt;add_from_resource("/toolbar/toolbar.glade");

Gtk::Button button("example");
gtk_button_do_something_that_gtkmm_cannot(button.gobj());

Gtk::DrawingArea myArea;
auto gdkCairoContext = myArea.get_surface()-&gt;create_cairo_context();
auto myContext = gdkCairoContext-&gt;cairo_create();
myContext-&gt;set_source_rgb(1.0, 0.0, 0.0);
myContext-&gt;set_line_width(2.0);
    
Gtk::Widget* CustomPrintOperation::on_create_custom_widget()
{
  set_custom_tab_label("My custom tab");

  auto hbox = new Gtk::Box(Gtk::Orientation::HORIZONTAL, 8);
  hbox-&gt;set_margin(6);

  auto label = Gtk::make_managed&lt;Gtk::Label&gt;("Enter some text: ");
  hbox-&gt;append(*label);

  hbox-&gt;append(m_Entry);

  return hbox;
}

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

GtkButton* cbutton = get_a_button();
Gtk::Button* button = Glib::wrap(cbutton);
button-&gt;set_label("Now I speak C++ too!");

GtkSizeRequestMode gtk_widget_get_request_mode(GtkWidget* widget);

GtkToolItem* gtk_tool_button_new(GtkWidget* icon_widget, const gchar* label);

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()
{
  auto pButton = Gtk::make_managed&lt;Gtk::Button&gt;("Test");
  append(*pButton); //add *pButton to MyContainer
}

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

_CLASS_BOXEDTYPE_STATIC(Rectangle, GdkRectangle)

_CLASS_GENERIC(TimeCoord, GdkTimeCoord)

_CLASS_GOBJECT(Adjustment, GtkAdjustment, GTK_ADJUSTMENT, Glib::Object, GObject)

_CLASS_GTKOBJECT(Button, GtkButton, GTK_BUTTON, Gtk::Widget, GtkWidget)

_CLASS_INTERFACE(CellEditable, GtkCellEditable, GTK_CELL_EDITABLE, GtkCellEditableIface)

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

_CLASS_OPAQUE_COPYABLE(VariantType, GVariantType, NONE, g_variant_type_copy, g_variant_type_free)

_CLASS_OPAQUE_REFCOUNTED(CssSection, GtkCssSection, NONE, gtk_css_section_ref, gtk_css_section_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_flow_box_set_filter_func, gtk_flow_box_set_sort_func)
_IGNORE_SIGNAL(activate-cursor-child, toggle-cursor-child, move-cursor)

_IMPLEMENTS_INTERFACE(Orientable)

_INITIALIZATION(`Gdk::Rectangle&amp;',`GdkRectangle',`$3 = Glib::wrap(&amp;($4))')

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

_INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 = ($1)($4)')

_INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 = (SizeRequestMode)($4)')

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

_WRAP_CTOR(ToolButton(Widget&amp; icon_widget, const Glib::ustring&amp; label{?}),
  gtk_tool_button_new)

_WRAP_ENUM(IconLookupFlags, GtkIconLookupFlags, NO_GTYPE)
      
_WRAP_ENUM(Orientation, GtkOrientation)

_WRAP_ENUM(ProxyFlags, GDBusProxyFlags, gtype_func g_dbus_proxy_flags_get_type)
      
_WRAP_ENUM(ResponseType, GtkResponseType, CONV_TO_INT)
      
_WRAP_ENUM(SeekType, GSeekType, NO_GTYPE, s#^SEEK_#SEEK_TYPE_#)
      
_WRAP_GERROR(PixbufError, GdkPixbufError, GDK_PIXBUF_ERROR)

_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)

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

_WRAP_METHOD_DOCS_ONLY(gtk_recent_info_get_applications)

_WRAP_PROPERTY("label", Glib::ustring)

_WRAP_SIGNAL(void clicked(),"clicked")

_WRAP_VFUNC(SizeRequestMode get_request_mode() const, get_request_mode)

auto builder = Gtk::Builder::create_from_file("basic.glade");

auto builder = Gtk::Builder::create_from_file("basic.glade", "treeview_products");

auto children = refModel-&gt;children();
for (auto iter = children.begin(), end = children.end(); iter != end; ++iter)
{
  auto row = *iter;
  //Do something with the row - see above for set/get.
}
auto gmenu = m_refBuilder-&gt;get_object&lt;Gio::Menu&gt;("menubar");
auto pMenuBar = Gtk::make_managed&lt;Gtk::MenuBar&gt;(gmenu);
m_Box.append(*pMenuBar);

auto toolbar = m_refBuilder-&gt;get_widget&lt;Gtk::Toolbar&gt;("toolbar");
m_Box.append(*toolbar);

auto op = Gtk::PrintOperation::create();
// ...set up op...
op-&gt;set_export_filename("test.pdf");
auto res = op-&gt;run(Gtk::PrintOperation::Action::EXPORT);

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

// do something useful with pButton

delete pButton;

auto pColumn = Gtk::make_managed&lt;Gtk::TreeView::Column&gt;("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);
auto pDialog = Gtk::Builder::get_widget_derived&lt;DerivedDialog&gt;(builder, "DialogDerived");

auto pDialog = Gtk::Builder::get_widget_derived&lt;DerivedDialog&gt;(builder, "DialogDerived", true);

auto pDialog = builder-&gt;get_widget&lt;Gtk::Dialog&gt;("DialogBasic");

auto pRenderer = Gtk::make_managed&lt;Gtk::CellRendererToggle&gt;();
pRenderer-&gt;signal_toggled().connect(
    sigc::bind( sigc::mem_fun(*this,
        &amp;Example_TreeView_TreeStore::on_cell_toggled), m_columns.dave)
);
auto pixbuf = Gdk::Pixbuf::create_from_file(filename);

auto pixbuf2 = pixbuf;

auto prefs_dialog = ExampleAppPrefs::create(*get_active_window());
prefs_dialog-&gt;present();

auto rb1 = Gtk::make_managed&lt;Gtk::CheckButton&gt;("button1");
auto rb2 = Gtk::make_managed&lt;Gtk::CheckButton&gt;("button2");
auto rb3 = Gtk::make_managed&lt;Gtk::CheckButton&gt;("button3");
rb2-&gt;set_group(*rb1);
rb3-&gt;set_group(*rb1);

auto refModel = m_TreeView.get_model();
if (refModel)
{
  auto cols_count = refModel-&gt;get_n_columns();
  ...
}

auto refPixbuf = Gdk::Pixbuf::create_from_file(filename);
auto refPixbuf2 = refPixbuf;

auto refPixbuf = Gdk::Pixbuf::create_from_file(filename);
auto width = refPixbuf-&gt;get_width();

auto refPixbuf = Gdk::Pixbuf::create_from_file(filename);
auto&amp; underlying = *refPixbuf; // Possible, but not recommended

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

auto refStore = std::dynamic_pointer_cast&lt;Gtk::TreeStore&gt;(refModel);
auto refStore2 = std::static_pointer_cast&lt;Gtk::TreeStore&gt;(refModel);

auto tag = buffer-&gt;create_tag();
m_settings-&gt;bind("font", tag-&gt;property_font());
buffer-&gt;apply_tag(tag, buffer-&gt;begin(), buffer-&gt;end());

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

bool ExampleWindow::on_button_press_event(GdkEventButton* event)
{
  if( (event-&gt;type == GDK_BUTTON_PRESS) &amp;&amp; (event-&gt;button == 3) )
  {
    if(!m_pMenuPopup-&gt;get_attach_widget())
      m_pMenuPopup-&gt;attach_to_widget(*this);

    m_pMenuPopup-&gt;popup(event-&gt;button, event-&gt;time);
    return true; //It has been handled.
  }
  else
    return false;
}

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) );

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

class Derived : public Glib::Object
{
  _CLASS_GOBJECT(Derived, GDerived, G_DERIVED, Glib::Object, GObject)

  _CUSTOM_MOVE_OPERATIONS

public:
  Derived(Derived&amp;&amp; src) noexcept;
  Derived&amp; operator=(Derived&amp;&amp; src) noexcept;
  // ...
};

class Server
{
public:
  //signal accessor:
  using type_signal_something = sigc::signal&lt;void(bool, int)&gt;;
  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'

for (auto row: refModel-&gt;children())
{
  //Do something with the row - see above for set/get.
}
gboolean gtk_icon_view_get_cell_rect(GtkIconView* icon_view,
  GtkTreePath* path, GtkCellRenderer* cell, GdkRectangle* rect);

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

m_refActionGroup = Gio::SimpleActionGroup::create();

m_refActionGroup-&gt;add_action("new", sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_new));
m_refActionGroup-&gt;add_action("open", sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_open));
m_refActionGroup-&gt;add_action("quit", sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_quit));

insert_action_group("example", m_refActionGroup);

m_refBuilder = Gtk::Builder::create();

app-&gt;set_accel_for_action("example.new", "&lt;Primary&gt;n");
app-&gt;set_accel_for_action("example.quit", "&lt;Primary&gt;q");
app-&gt;set_accel_for_action("example.copy", "&lt;Primary&gt;c");
app-&gt;set_accel_for_action("example.paste", "&lt;Primary&gt;v");

m_settings = Gio::Settings::create("org.gtkmm.exampleapp");
m_settings-&gt;bind("transition", m_stack-&gt;property_transition_type());

my_connection.disconnect();

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

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

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

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

typedef struct _ExampleWidget ExampleWidget;

struct _ExampleWidget
{
  ...
};

void ExampleAppWindow::on_search_text_changed()
{
  const auto text = m_searchentry-&gt;get_text();
  auto tab = dynamic_cast&lt;Gtk::ScrolledWindow*&gt;(m_stack-&gt;get_visible_child());
  auto view = dynamic_cast&lt;Gtk::TextView*&gt;(tab-&gt;get_child());

  // Very simple-minded search implementation.
  auto buffer = view-&gt;get_buffer();
  Gtk::TextIter match_start;
  Gtk::TextIter match_end;
  if (buffer-&gt;begin().forward_search(text, Gtk::TextSearchFlags::CASE_INSENSITIVE,
      match_start, match_end))
  {
    buffer-&gt;select_range(match_start, match_end);
    view-&gt;scroll_to(match_start);
  }
}

void ExampleWindow::on_printoperation_done(Gtk::PrintOperationResult result,
  const Glib::RefPtr&lt;PrintOperation&gt;&amp; op)
{
  if (result == Gtk::PrintOperation::Result::ERROR)
    //notify user
  else if (result == Gtk::PrintOperation::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;PrintOperation&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 gtk_widget_set_device_events(GtkWidget* widget, GdkDevice* device,
  GdkEventMask events);

void init()
{
  Gtk::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;

int 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_button_clicked(const Glib::ustring&amp; data);

void on_insert(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#! /bin/sh -e
test -n "$srcdir" || srcdir=`dirname "$0"`
test -n "$srcdir" || srcdir=.

autoreconf --force --install --verbose --warnings=all "$srcdir"
echo "Running intltoolize --copy --force --automake"
intltoolize --copy --force --automake
test -n "$NOCONFIGURE" || "$srcdir/configure" "$@"#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)')$ cp examples/sample.jhbuildrc ~/.config/jhbuildrc$ glib-compile-resources --target=resources.c --generate-source exampleapp.gresource.xml$ glib-compile-resources --target=resources.c --generate-source image.gresource.xml$ glib-compile-resources --target=resources.c --generate-source toolbar.gresource.xml$ jhbuild bootstrap
$ jhbuild sanitycheck(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];<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>cairo</application><application>cairomm-1.16</application><application>gdk-pixbuf-2.0</application><application>glib-2.0</application><application>glibmm-2.68</application><application>graphene-1.0</application><application>gtk4</application><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> 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> 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> 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> 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 four basic types of buttons:<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>, 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>pango</application><application>pangomm-2.48</application><application>pkg-config</application><application>sigc++-3.0</application><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>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>, <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::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::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::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::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>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>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>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>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:<filename>/toolbar/rain.png</filename><filename>/toolbar/toolbar.glade</filename><filename>gtk.defs</filename><filename>gtk_enums.defs</filename><filename>gtk_vfuncs.defs</filename><filename>libsomething</filename>: Contains the main include file and the pkg-config .pc file.<filename>libsomethingmm</filename>: The top-level directory.<filename>skeleton/skeletonmm/meson.build</filename><filename>src</filename>: Contains .hg and .ccg source files.<firstname>Murray</firstname> <surname>Cumming</surname><function>_CLASS_BOXEDTYPE( C++ class, C class, new function, copy function, free function )</function><function>_CLASS_BOXEDTYPE_STATIC( C++ class, C class )</function><function>_CLASS_GENERIC( C++ class, C class )</function><function>_CLASS_GOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )</function><function>_CLASS_GTKOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )</function><function>_CLASS_GTKOBJECT()</function><function>_CLASS_INTERFACE( C++ class, C class, C casting macro, C interface struct, Base C++ class (optional), Base C class (optional) )</function><function>_CLASS_OPAQUE_COPYABLE( C++ class, C class, new function, copy function, free function )</function><function>_CLASS_OPAQUE_REFCOUNTED( C++ class, C class, new function, ref function, unref function )</function><function>_CTOR_DEFAULT</function><function>_DEFS()</function><function>_IGNORE(C function name 1, C function name 2, etc)
_IGNORE_SIGNAL(C signal name 1, C signal name 2, etc)
_IGNORE_PROPERTY(C property name 1, C property name 2, etc)</function><function>_IMPLEMENTS_INTERFACE()</function><function>_IMPLEMENTS_INTERFACE(C++ interface name)</function><function>_MEMBER_GET(C++ name, C name, C++ type, C type)</function><function>_MEMBER_GET_GOBJECT(C++ name, C name, C++ type, C type)</function><function>_MEMBER_GET_PTR(C++ name, C name, C++ type, C type)</function><function>_MEMBER_SET(C++ name, C name, C++ type, C type)</function><function>_MEMBER_SET_GOBJECT(C++ name, C name, C++ type, C type)</function><function>_MEMBER_SET_PTR(C++ name, C name, C++ type, C type)</function><function>_PINCLUDE()</function><function>_WRAP_METHOD()</function>, <function>_WRAP_SIGNAL()</function>, and <function>_WRAP_PROPERTY()</function><function>_WRAP_PROPERTY(C property name, C++ type)</function><function>_WRAP_SIGNAL( C++ signal handler signature, C signal name)</function><function>_WRAP_VFUNC( C++ method signature, C function name)</function><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>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>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_data_delete</literal>: Gives the source the opportunity to delete the original data if that's appropriate.<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_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>upper</literal>: upper range value<literal>value</literal>: value for the Spin Button<methodname>drag_dest_add_text_targets()</methodname><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>on_map()</methodname>: (optional)<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)<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.<type>bool</type><type>double</type><type>gboolean</type><type>gchar*</type><type>gdouble</type><type>gint</type><type>guint</type><type>gunichar</type><type>int</type><ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1RefPtr.html">Reference</ulink><ulink url="http://developer.gnome.org/glibmm/unstable/namespaceGlib.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGdk_1_1Clipboard.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1AboutDialog.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1AspectFrame.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Assistant.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Box.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Builder.html">Reference</ulink><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_1Button.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1CheckButton.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ColorChooserDialog.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ComboBox.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Dialog.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Entry.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1EntryCompletion.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1FileChooserDialog.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1FontChooserDialog.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Frame.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Grid.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1InfoBar.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Label.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ListStore.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1MessageDialog.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Notebook.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1PageSetup.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Paned.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1PrintOperation.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ProgressBar.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1RadioButton.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Range.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Scale.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Scrollbar.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ScrolledWindow.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1SpinButton.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextBuffer.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextChildAnchor.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextIter.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextMark.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextTag.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextTagTable.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextView.html">Reference</ulink><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.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToggleButton.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Tooltip.html">Tooltip Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeModel.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeStore.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeView.html">Reference</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Widget.html">Widget Reference</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/aspectframe">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/assistant/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/base">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/box">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step1">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step2">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step3">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step4">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step5">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step6">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step7">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step8">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step9">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/builder/basic">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buttons/button">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buttons/checkbutton">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buttons/radiobutton">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/clipboard/ideal/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/clipboard/simple/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/combobox/complex">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/combobox/entry_complex">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/combobox/entry_text">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/combobox/text">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/custom/custom_container/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/custom/custom_widget/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/aboutdialog">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/colorchooserdialog">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/filechooserdialog">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/fontchooserdialog">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/messagedialog">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/arcs">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/clock">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/curve">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/image">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/pango_text">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/simple">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/thin_lines">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/entry/completion">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/entry/icon">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/entry/progress">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/entry/simple">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/frame">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/grid">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/helloworld2">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/idle/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/infobar">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/input/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/keyboard_events/propagation/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/keyboard_events/simple/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/label">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/menus/main_menu/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/menus/popup/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/menus_and_toolbars">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/multithread">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/notebook/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/paned">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/printing/simple/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/progressbar">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/range_widgets">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/recent_files">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/scrolledwindow">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/signals/custom/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/spinbutton">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/textview/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/timeout/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/tooltips">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/drag_and_drop/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/editable_cells/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/list/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/popup/">Source Code</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/tree/">Source Code</ulink><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>defs_basefiles</varname><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>extra_cc_files, extra_h_files</varname><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>hg_ccg_basenames</varname><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 resource<year>2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010</year> <holder>Murray Cumming</holder>A <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>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>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>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 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.AM_CPPFLAGS = ... -DPROGRAMNAME_LOCALEDIR=\"${PROGRAMNAME_LOCALEDIR}\"AboutDialogAccessing widgetsActionsActivity ModeAdd <literal>po</literal> to the <literal>SUBDIRS</literal> variable. Without this, your translations won't get built and installed when you build the programAdd 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 widgetsAdditionally, mouse button 3 can be used to jump directly to the <literal>upper</literal> or <literal>lower</literal> values.Adjustment InternalsAdjustmentsAfter 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 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 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.All <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 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.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 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 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.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 WorldAnother 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.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.Application LifetimeApplying TagsAs 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 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.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.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.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.Besides 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 2BoxesButtonButtonsBy 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 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.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++ typeCONV_TO_INTCairo and PangoCastingChanges 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 selectionCheckButtonChild 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>.Class 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 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 macrosContainer 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 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 signalsCurrently, <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-cacheDeclare 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 formattingDependenciesDereferencingDesigners 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 join types in CairoDisconnecting signal handlersDo 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.DocumentationDocumentation build structureDrag and DropDrawing 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 coordinatesDynamic allocation with new and deleteEach <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.Editable CellsEntryEntry 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.ExampleExample Application: Creating a Clock with CairoExamplesExceptions in signal handlersExpecting UTF8Export to PDFExtending the print dialogFileChooserFileChooserDialogFontChooserDialogFor a CellRendererToggle, you would set the <emphasis>activatable</emphasis> property instead.For example: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, for a CellRendererText, you would set the cell's <emphasis>editable</emphasis> property to true, like so:For instance, this code would be problematic:For instance:For more detailed information about signals, see the <link linkend="chapter-signals">appendix</link>.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.FrameFull ExampleFunction scope widgetsGLib::ustring text(C_("noun", "jumps"));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 .defsGet the data from the widgets in the <literal>custom_widget_apply</literal> signal handler.Getting help with translationsGetting valuesGlade 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::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::ustringGlib::ustring and std::iostreamsGridGroupsGtk::Application and command-line optionsGtk::Box(Gtk::Orientation orientation = Gtk::Orientation::HORIZONTAL, int spacing = 0);
void set_orientation(Gtk::Orientation orientation);
void set_spacing(int spacing);
void set_homogeneous(bool homogeneous = true);Gtk::Button* pButton = new Gtk::Button("_Something", true);Gtk::ComboBox now derives from CellLayout, allowing easier layout and alignment of its <classname>Gtk::CellRenderer</classname>s.Gtk::IconTheme::get_for_display(get_display())-&gt;add_resource_path("/org/gtkmm/exampleapp");
set_icon_name("exampleapp");

Gtk::TreeModel::Children children = row.children();Gtk::TreeModel::iterator iter = m_Combo.get_active();
if(iter)
{
  auto row = *iter;

  //Get the data for the selected row, using our knowledge
  //of the tree model:
  auto id = row[m_Columns.m_col_id];
  set_something_id_chosen(id); //Your own function.
}
else
  set_nothing_chosen(); //Your own function.Gtk::Window window;
window.set_default_size(200, 200);Hand-coded source filesHand-coding constructorsHandling <literal>button_press_event</literal>Header barHeaders and LinkingHello WorldHello World 2Hello World in <application>gtkmm</application>HelloWorld::HelloWorld()
: m_button("Hello World")
{
  m_button.set_margin(10);
  m_button.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;HelloWorld::on_button_clicked));
  set_child(m_button);
}Here are some examples of normal C++ memory management: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 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 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:How gettext worksHowever, 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>.INTLTOOL_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_GNU_GETTEXT([external])
AM_GNU_GETTEXT_VERSION([0.17])

PROGRAMNAME_LOCALEDIR=[${datadir}/locale]
AC_SUBST(PROGRAMNAME_LOCALEDIR)IdealIdle 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 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 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 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 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'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.Implementing custom logic for editable cells.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 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 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 modelInfoBarInitializationInstallationInstalling <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.Internationalization and LocalizationIntroductionIt 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'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 RowsIteratorsJust 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 - SimpleLabelLack of propertiesLess 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 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 exampleManaged 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 translationMarksMaybe 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.Memory managementMenus and ToolbarsMessageDialogMethod macrosMethodsMicrosoft WindowsMiscellaneous WidgetsMixing C and C++ APIsModel ColumnsModifying build filesModifying the List of Recent FilesMonitoring I/OMore than one Model Column per View ColumnMost 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.MoveMulti-Threaded ProgramMulti-threaded programsNO_GTYPENicolai M. Josuttis, "The C++ Standard Library" - section 4.2Non-modal AboutDialogNormal C++ memory managementNote 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 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 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, 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 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'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.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 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.On 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.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.Optional Parameter ProcessingOther 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.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-4.0 &gt;= 4.8.0])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).Parameter ReorderingPastePer-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.PitfallsPopup 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 - SimpleProblems in the C API.Progress 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.ProgressBarPuts 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 WidgetsRecent 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.RecentManagerRecently Used DocumentsRecommended TechniquesRemember 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 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 documentationRow childrenSame strings, different semanticsScale WidgetsScrollbar WidgetsScrolledWindowScrollingSee <link linkend="sec-printing-example-simple">an example</link> of exactly how this can be done.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.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 resourcesSignal 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 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 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, 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: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).SortingSorting by clicking on columnsSources 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 detailsSpinButtonString 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.TagTableTagsTags and FormattingTells <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 .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 <classname>AboutDialog</classname> offers a simple way to display information about a program, like its logo, name, copyright, website and license.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>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::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>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>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 <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 <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 BufferThe 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 ModelThe RefPtr smartpointerThe SelectionThe TreeView widgetThe 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 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 compiler will complain if you use an inappropriate type. For instance, this would generate a compiler error:The constraintsThe 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 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 call to <methodname>connect()</methodname> is just like the one we saw last time; nothing new here.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 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 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 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 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 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 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 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 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 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 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 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 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 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.Then, to add a widget at that position, use <methodname>Gtk::TextView::add_child_at_anchor()</methodname>: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 other containers, which we will also discuss.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 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 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 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.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 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 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 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 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 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 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 involves a variety of tools, some of them crufty, but at least they work, and has been used successfully by several projects.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 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 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 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>.TimeoutsTimeouts, I/O and Idle FunctionsTo 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 control which rows can be selected, use the <methodname>set_select_function()</methodname> method, providing a <classname>sigc::slot</classname> callback. For instance: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 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 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 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 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 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 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 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:Toggle buttonsToggleButtonTooltipTooltipsTreeStoreTreeStore, 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:UI changes can be seen more quickly, so UIs are able to improve.Unable to predeclare structsUnix and LinuxUnlike 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.Unusual wordsUse <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 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 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>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 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 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 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.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 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 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 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 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.Widget::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 and ChildAnchorsWith 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 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 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 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 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 use the <methodname>get_iter()</methodname> method later to create an iterator for the <classname>Mark</classname>'s new position.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>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 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 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 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 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 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 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 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'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 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._CLASS_BOXEDTYPE_CLASS_BOXEDTYPE_STATIC_CLASS_GENERIC_CLASS_GOBJECT_CLASS_GTKOBJECT_CLASS_INTERFACE_CLASS_OPAQUE_COPYABLE_CLASS_OPAQUE_REFCOUNTED_CTOR_DEFAULT_CUSTOM_CTOR_CAST_CUSTOM_DTOR_CUSTOM_MOVE_OPERATIONS_CUSTOM_WRAP_FUNCTION_CUSTOM_WRAP_NEW_IGNORE, _IGNORE_SIGNAL, _IGNORE_PROPERTY_IMPLEMENTS_INTERFACE_MEMBER_GET / _MEMBER_SET_MEMBER_GET(x, x, int, int)_MEMBER_GET_GOBJECT / _MEMBER_SET_GOBJECT_MEMBER_GET_PTR / _MEMBER_SET_PTR_NO_WRAP_FUNCTION_WRAP_CTOR_WRAP_ENUM_WRAP_ENUM_DOCS_ONLY_WRAP_GERROR_WRAP_METHOD_WRAP_METHOD_DOCS_ONLY_WRAP_PROPERTY_WRAP_SIGNAL_WRAP_VFUNCadd_action(Gio::PropertyAction::create("show-lines", m_lines-&gt;property_visible()));
m_binding_lines_visible = Glib::Binding::bind_property(m_lines-&gt;property_visible(),
  m_lines_label-&gt;property_visible());

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 thenauto app = Gtk::Application::create("org.gtkmm.examples.base");auto cols_count = m_TreeView.append_column_editable("Alex", m_columns.alex);
auto pColumn = m_TreeView.get_column(cols_count-1);
if(pColumn)
{
  auto 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);auto entry = m_Combo.get_entry();
if (entry)
{
  // 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) );
}auto iter = m_refListStore-&gt;append();auto iter = m_refModel-&gt;children().begin()
if(iter)
  refTreeSelection-&gt;select(iter);auto iter = refTreeSelection-&gt;get_selected();
if(iter) //If anything is selected
{
  auto row = *iter;
  //Do something with the row.
}auto iter_child =
    m_refTreeStore-&gt;append(row.children());auto pColumn = treeview.get_column(0);
if(pColumn)
  pColumn-&gt;set_sort_column(m_columns.m_col_id);auto refTagMatch = Gtk::TextBuffer::Tag::create();
refTagMatch-&gt;property_background() = "orange";auto 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.
auto refBuffer = Gtk::TextBuffer::create(refTagTable);auto row = *iter;auto row = m_refModel-&gt;children()[5]; //The sixth row.
if(row)
  refTreeSelection-&gt;select(row.get_iter());auto sorted_model = Gtk::TreeModelSort::create(model);
sorted_model-&gt;set_sort_column(columns.m_col_name, Gtk::SORT_ASCENDING);
treeview.set_model(sorted_model);auto strText = row[m_Columns.m_col_text];
auto number = row[m_Columns.m_col_number];bindtextdomain(GETTEXT_PACKAGE, PROGRAMNAME_LOCALEDIR);
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
textdomain(GETTEXT_PACKAGE);bool DemoWindow::select_function(
    const Glib::RefPtr&lt;Gtk::TreeModel&gt;&amp; model,
    const Gtk::TreeModel::Path&amp; path, bool)
{
  const auto iter = model-&gt;get_iter(path);
  return iter-&gt;children().empty(); // only allow leaf nodes to be selected
}buttons exampleclass HelloWorld : public Gtk::Window
{
public:
  HelloWorld();
  ~HelloWorld() override;

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

  //Member widgets:
  Gtk::Button m_button;
};class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
  ModelColumns()
  { 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;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;constversioncontext-&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_callbackdeprecated ["&lt;text&gt;"]desktopdir = $(datadir)/applications
desktop_in_files = programname.desktop.in
desktop_DATA = $(desktop_in_files:.desktop.in=.desktop)
@INTLTOOL_DESKTOP_RULE@detail_name &lt;parameter_name&gt;display_message("Getting ready for i18n.");display_message(_("Getting ready for i18n."));enumserr_return_value &lt;value&gt;errthrowerrthrow ["&lt;exceptions&gt;"]exception_handler &lt;method_name&gt;functionsg++ simple.cc -o simple `pkg-config gtkmm-4.0 --cflags --libs`gmmproc Parameter Processinggtkmmifdef &lt;identifier&gt;int main(int argc, char* argv[])
{
  auto app = Gtk::Application::create("org.gtkmm.example");
  HelloWorld helloworld;
  return app-&gt;run(helloworld, argc, argv);
}intltool-update --potkeep_returnm4 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.append(m_Button1);
m_box.append(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.set_child(m_box);m_refTreeSelection-&gt;set_select_function( sigc::mem_fun(*this,
    &amp;DemoWindow::select_function) );modules = [ 'gtkmm' ]newin "&lt;version&gt;"no_default_handlerno_slot_copyobjects (GObjects, widgets, interfaces, boxed-types and plain structs)orpropertiesrefBuffer-&gt;apply_tag(refTagMatch, iterRangeStart, iterRangeStop);refBuffer-&gt;insert_with_tag(iter, "Some text", refTagMatch);refTreeSelection-&gt;selected_foreach_iter(
    sigc::mem_fun(*this, &amp;TheClass::selected_row_callback) );

void TheClass::selected_row_callback(
    const Gtk::TreeModel::const_iterator&amp; iter)
{
  auto 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_ctypereturn app-&gt;run(window, argc, argv);return_value &lt;value&gt;row[m_Columns.m_col_text] = "sometext";s#&lt;from&gt;#&lt;to&gt;#signalsslot_callback &lt;function_name&gt;slot_name &lt;parameter_name&gt;src/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::locale::global(std::locale("")); // Set the global locale to the user's preferred locale.
                                      // Usually unnecessary here, because Glib::init()
                                      // or Gtk::Application::create() does it for you.
std::ostringstream output;
output &lt;&lt; percentage &lt;&lt; " % done";
label-&gt;set_text(Glib::locale_to_utf8(output.str()));vfuncsvfuncs (function pointer member fields in structs), written by hand.void ExampleWindow::on_button_copy()
{
  get_clipboard()-&gt;set_text("example_custom_target");
}void ExampleWindow::on_button_delete()
{
  auto refTreeSelection = m_treeview.get_selection();
  if(refTreeSelection)
  {
    auto sorted_iter = m_refTreeSelection-&gt;get_selected();
    if(sorted_iter)
    {
      auto iter = m_refModelSort-&gt;convert_iter_to_child_iter(sorted_iter);
      m_refModel-&gt;erase(iter);
    }
  }
}void ExampleWindow::on_button_paste()
{
  get_clipboard()-&gt;read_text_async(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_clipboard_received));
}void ExampleWindow::on_clipboard_received(Glib::RefPtr&lt;Gio::AsyncResult&gt;&amp; result)
{
  auto text = get_clipboard()-&gt;read_text_finish(result);
  //Do something with the pasted data.
}void MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr, int width, int height)
{
  auto 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();
}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();
}voidreturnwhere <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).xgettext -a -o my-strings --omit-header *.cc *.hProject-Id-Version: gtkmm-documentation.tutorial.master
PO-Revision-Date: 2021-01-13 13:43+0100
Last-Translator: Daniel Mustieles <daniel.mustieles@gmail.com>
Language-Team: Spanish - Spain <gnome-es-list@gnome.org>
Language: es_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 3.38.0

    ...
    button.signal_clicked().connect(sigc::ptr_fun(&amp;on_button_clicked));
    ...

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

# ./configure --prefix=/usr

#include &lt;glibmm_generate_extra_defs/generate_extra_defs.h&gt;
#include &lt;libsomething.h&gt;
#include &lt;iostream&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;
}

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

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

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;
}

int 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;gtkmm/widget.h&gt;
#include &lt;gtkmm/actionable.h&gt;
_DEFS(gtkmm,gtk)
_PINCLUDE(gtkmm/private/widget_p.h)

namespace Gtk
{

class Button
  : public Widget,
    public Actionable
{
  _CLASS_GTKOBJECT(Button, GtkButton, GTK_BUTTON, Gtk::Widget, GtkWidget)
  _IMPLEMENTS_INTERFACE(Actionable)
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

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

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

$ cd gtk/src
$ /usr/lib/glibmm-2.68/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

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;gresources&gt;
  &lt;gresource prefix="/toolbar"&gt;
    &lt;file preprocess="xml-stripblanks"&gt;toolbar.glade&lt;/file&gt;
    &lt;file&gt;rain.png&lt;/file&gt;
  &lt;/gresource&gt;
&lt;/gresources&gt;

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

// Connect the menu to the MenuButton m_gears, and bind the show-words setting
// to the win.show-words action and the "Words" menu item.
// (The connection between action and menu item is specified in gears_menu.ui.)
auto menu_builder = Gtk::Builder::create_from_resource("/org/gtkmm/exampleapp/gears_menu.ui");
auto menu = menu_builder-&gt;get_object&lt;Gio::MenuModel&gt;("menu");
m_gears-&gt;set_menu_model(menu);
add_action(m_settings-&gt;create_action("show-words"));

// Within a class that inherits from Gtk::Window and keeps m_refPageSetup
// and m_refSettings as members...
auto new_page_setup = Gtk::run_page_setup_dialog(*this, m_refPageSetup, m_refSettings);
m_refPageSetup = new_page_setup;

// _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...
auto op = PrintOperation::create();
// ...set up op...
op-&gt;run(Gtk::PrintOperation::Action::PREVIEW, *this);

// in class ExampleWindow's method...
auto 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);
  auto app = Gtk::Application::create("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();
  auto app = Gtk::Application::create("org.gtkmm.without_signal");
  return app-&gt;run();
}

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

DerivedButton::DerivedButton(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder)
: Glib::ObjectBase("MyButton"), // The GType name will be gtkmm__CustomObject_MyButton.
  Gtk::Button(cobject),
  prop_ustring(*this, "button-ustring"),
  prop_int(*this, "button-int", 10)
{
  // ....
}

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),
  //Get the Glade-instantiated Button, and connect a signal handler:
  m_pButton(m_builder-&gt;get_widget&lt;Gtk::Button&gt;("quit_button"))
{
  if(m_pButton)
  {
    m_pButton-&gt;signal_clicked().connect( sigc::mem_fun(*this, &amp;DerivedDialog::on_button_quit) );
  }
}

DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder, bool warning)
: Gtk::Dialog(cobject),
  m_builder(builder),
  m_pButton(m_builder-&gt;get_widget&lt;Gtk::Button&gt;("quit_button"))
{
  // ....
}

Glib::ustring ui_info =
  "&lt;interface&gt;"
  "  &lt;menu id='menu-examplepopup'&gt;"
  "    &lt;section&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;Edit&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;examplepopup.edit&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;Process&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;examplepopup.process&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;Remove&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;examplepopup.remove&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "    &lt;/section&gt;"
  "  &lt;/menu&gt;"
  "&lt;/interface&gt;";

m_refBuilder-&gt;add_from_string(ui_info);

auto gmenu = m_refBuilder-&gt;get_object&lt;Gio::Menu&gt;("menu-examplepopup");
m_pMenuPopup = std::make_unique&lt;Gtk::Menu&gt;(gmenu);

Glib::ustring ui_info =
  "&lt;interface&gt;"
  "  &lt;menu id='menubar'&gt;"
  "    &lt;submenu&gt;"
  "      &lt;attribute name='label' translatable='yes'&gt;_File&lt;/attribute&gt;"
  "      &lt;section&gt;"
  "        &lt;item&gt;"
  "          &lt;attribute name='label' translatable='yes'&gt;_New&lt;/attribute&gt;"
  "          &lt;attribute name='action'&gt;example.new&lt;/attribute&gt;"
  "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;n&lt;/attribute&gt;"
  "        &lt;/item&gt;"
  "      &lt;/section&gt;"
  "      &lt;section&gt;"
  "        &lt;item&gt;"
  "          &lt;attribute name='label' translatable='yes'&gt;_Quit&lt;/attribute&gt;"
  "          &lt;attribute name='action'&gt;example.quit&lt;/attribute&gt;"
  "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;q&lt;/attribute&gt;"
  "        &lt;/item&gt;"
  "      &lt;/section&gt;"
  "    &lt;/submenu&gt;"
  "    &lt;submenu&gt;"
  "      &lt;attribute name='label' translatable='yes'&gt;_Edit&lt;/attribute&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;_Copy&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;example.copy&lt;/attribute&gt;"
  "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;c&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "      &lt;item&gt;"
  "        &lt;attribute name='label' translatable='yes'&gt;_Paste&lt;/attribute&gt;"
  "        &lt;attribute name='action'&gt;example.paste&lt;/attribute&gt;"
  "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;v&lt;/attribute&gt;"
  "      &lt;/item&gt;"
  "    &lt;/submenu&gt;"
  "  &lt;/menu&gt;"
  "&lt;/interface&gt;";

m_refBuilder-&gt;add_from_string(ui_info);
m_refBuilder-&gt;add_from_resource("/toolbar/toolbar.glade");

Gtk::Button button("example");
gtk_button_do_something_that_gtkmm_cannot(button.gobj());

Gtk::DrawingArea myArea;
auto gdkCairoContext = myArea.get_surface()-&gt;create_cairo_context();
auto myContext = gdkCairoContext-&gt;cairo_create();
myContext-&gt;set_source_rgb(1.0, 0.0, 0.0);
myContext-&gt;set_line_width(2.0);
    
Gtk::Widget* CustomPrintOperation::on_create_custom_widget()
{
  set_custom_tab_label("My custom tab");

  auto hbox = new Gtk::Box(Gtk::Orientation::HORIZONTAL, 8);
  hbox-&gt;set_margin(6);

  auto label = Gtk::make_managed&lt;Gtk::Label&gt;("Enter some text: ");
  hbox-&gt;append(*label);

  hbox-&gt;append(m_Entry);

  return hbox;
}

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

GtkButton* cbutton = get_a_button();
Gtk::Button* button = Glib::wrap(cbutton);
button-&gt;set_label("Now I speak C++ too!");

GtkSizeRequestMode gtk_widget_get_request_mode(GtkWidget* widget);

GtkToolItem* gtk_tool_button_new(GtkWidget* icon_widget, const gchar* label);

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()
{
  auto pButton = Gtk::make_managed&lt;Gtk::Button&gt;("Test");
  append(*pButton); //add *pButton to MyContainer
}

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

_CLASS_BOXEDTYPE_STATIC(Rectangle, GdkRectangle)

_CLASS_GENERIC(TimeCoord, GdkTimeCoord)

_CLASS_GOBJECT(Adjustment, GtkAdjustment, GTK_ADJUSTMENT, Glib::Object, GObject)

_CLASS_GTKOBJECT(Button, GtkButton, GTK_BUTTON, Gtk::Widget, GtkWidget)

_CLASS_INTERFACE(CellEditable, GtkCellEditable, GTK_CELL_EDITABLE, GtkCellEditableIface)

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

_CLASS_OPAQUE_COPYABLE(VariantType, GVariantType, NONE, g_variant_type_copy, g_variant_type_free)

_CLASS_OPAQUE_REFCOUNTED(CssSection, GtkCssSection, NONE, gtk_css_section_ref, gtk_css_section_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_flow_box_set_filter_func, gtk_flow_box_set_sort_func)
_IGNORE_SIGNAL(activate-cursor-child, toggle-cursor-child, move-cursor)

_IMPLEMENTS_INTERFACE(Orientable)

_INITIALIZATION(`Gdk::Rectangle&amp;',`GdkRectangle',`$3 = Glib::wrap(&amp;($4))')

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

_INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 = ($1)($4)')

_INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 = (SizeRequestMode)($4)')

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

_WRAP_CTOR(ToolButton(Widget&amp; icon_widget, const Glib::ustring&amp; label{?}),
  gtk_tool_button_new)

_WRAP_ENUM(IconLookupFlags, GtkIconLookupFlags, NO_GTYPE)
      
_WRAP_ENUM(Orientation, GtkOrientation)

_WRAP_ENUM(ProxyFlags, GDBusProxyFlags, gtype_func g_dbus_proxy_flags_get_type)
      
_WRAP_ENUM(ResponseType, GtkResponseType, CONV_TO_INT)
      
_WRAP_ENUM(SeekType, GSeekType, NO_GTYPE, s#^SEEK_#SEEK_TYPE_#)
      
_WRAP_GERROR(PixbufError, GdkPixbufError, GDK_PIXBUF_ERROR)

_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)

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

_WRAP_METHOD_DOCS_ONLY(gtk_recent_info_get_applications)

_WRAP_PROPERTY("label", Glib::ustring)

_WRAP_SIGNAL(void clicked(),"clicked")

_WRAP_VFUNC(SizeRequestMode get_request_mode() const, get_request_mode)

auto builder = Gtk::Builder::create_from_file("basic.glade");

auto builder = Gtk::Builder::create_from_file("basic.glade", "treeview_products");

auto children = refModel-&gt;children();
for (auto iter = children.begin(), end = children.end(); iter != end; ++iter)
{
  auto row = *iter;
  //Do something with the row - see above for set/get.
}
auto gmenu = m_refBuilder-&gt;get_object&lt;Gio::Menu&gt;("menubar");
auto pMenuBar = Gtk::make_managed&lt;Gtk::MenuBar&gt;(gmenu);
m_Box.append(*pMenuBar);

auto toolbar = m_refBuilder-&gt;get_widget&lt;Gtk::Toolbar&gt;("toolbar");
m_Box.append(*toolbar);

auto op = Gtk::PrintOperation::create();
// ...set up op...
op-&gt;set_export_filename("test.pdf");
auto res = op-&gt;run(Gtk::PrintOperation::Action::EXPORT);

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

// do something useful with pButton

delete pButton;

auto pColumn = Gtk::make_managed&lt;Gtk::TreeView::Column&gt;("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);
auto pDialog = Gtk::Builder::get_widget_derived&lt;DerivedDialog&gt;(builder, "DialogDerived");

auto pDialog = Gtk::Builder::get_widget_derived&lt;DerivedDialog&gt;(builder, "DialogDerived", true);

auto pDialog = builder-&gt;get_widget&lt;Gtk::Dialog&gt;("DialogBasic");

auto pRenderer = Gtk::make_managed&lt;Gtk::CellRendererToggle&gt;();
pRenderer-&gt;signal_toggled().connect(
    sigc::bind( sigc::mem_fun(*this,
        &amp;Example_TreeView_TreeStore::on_cell_toggled), m_columns.dave)
);
auto pixbuf = Gdk::Pixbuf::create_from_file(filename);

auto pixbuf2 = pixbuf;

auto prefs_dialog = ExampleAppPrefs::create(*get_active_window());
prefs_dialog-&gt;present();

auto rb1 = Gtk::make_managed&lt;Gtk::CheckButton&gt;("button1");
auto rb2 = Gtk::make_managed&lt;Gtk::CheckButton&gt;("button2");
auto rb3 = Gtk::make_managed&lt;Gtk::CheckButton&gt;("button3");
rb2-&gt;set_group(*rb1);
rb3-&gt;set_group(*rb1);

auto refModel = m_TreeView.get_model();
if (refModel)
{
  auto cols_count = refModel-&gt;get_n_columns();
  ...
}

auto refPixbuf = Gdk::Pixbuf::create_from_file(filename);
auto refPixbuf2 = refPixbuf;

auto refPixbuf = Gdk::Pixbuf::create_from_file(filename);
auto width = refPixbuf-&gt;get_width();

auto refPixbuf = Gdk::Pixbuf::create_from_file(filename);
auto&amp; underlying = *refPixbuf; // Possible, but not recommended

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

auto refStore = std::dynamic_pointer_cast&lt;Gtk::TreeStore&gt;(refModel);
auto refStore2 = std::static_pointer_cast&lt;Gtk::TreeStore&gt;(refModel);

auto tag = buffer-&gt;create_tag();
m_settings-&gt;bind("font", tag-&gt;property_font());
buffer-&gt;apply_tag(tag, buffer-&gt;begin(), buffer-&gt;end());

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

bool ExampleWindow::on_button_press_event(GdkEventButton* event)
{
  if( (event-&gt;type == GDK_BUTTON_PRESS) &amp;&amp; (event-&gt;button == 3) )
  {
    if(!m_pMenuPopup-&gt;get_attach_widget())
      m_pMenuPopup-&gt;attach_to_widget(*this);

    m_pMenuPopup-&gt;popup(event-&gt;button, event-&gt;time);
    return true; //It has been handled.
  }
  else
    return false;
}

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) );

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

class Derived : public Glib::Object
{
  _CLASS_GOBJECT(Derived, GDerived, G_DERIVED, Glib::Object, GObject)

  _CUSTOM_MOVE_OPERATIONS

public:
  Derived(Derived&amp;&amp; src) noexcept;
  Derived&amp; operator=(Derived&amp;&amp; src) noexcept;
  // ...
};

class Server
{
public:
  //signal accessor:
  using type_signal_something = sigc::signal&lt;void(bool, int)&gt;;
  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'

for (auto row: refModel-&gt;children())
{
  //Do something with the row - see above for set/get.
}
gboolean gtk_icon_view_get_cell_rect(GtkIconView* icon_view,
  GtkTreePath* path, GtkCellRenderer* cell, GdkRectangle* rect);

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

m_refActionGroup = Gio::SimpleActionGroup::create();

m_refActionGroup-&gt;add_action("new", sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_new));
m_refActionGroup-&gt;add_action("open", sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_open));
m_refActionGroup-&gt;add_action("quit", sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_quit));

insert_action_group("example", m_refActionGroup);

m_refBuilder = Gtk::Builder::create();

app-&gt;set_accel_for_action("example.new", "&lt;Primary&gt;n");
app-&gt;set_accel_for_action("example.quit", "&lt;Primary&gt;q");
app-&gt;set_accel_for_action("example.copy", "&lt;Primary&gt;c");
app-&gt;set_accel_for_action("example.paste", "&lt;Primary&gt;v");

m_settings = Gio::Settings::create("org.gtkmm.exampleapp");
m_settings-&gt;bind("transition", m_stack-&gt;property_transition_type());

my_connection.disconnect();

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

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

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

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

typedef struct _ExampleWidget ExampleWidget;

struct _ExampleWidget
{
  ...
};

void ExampleAppWindow::on_search_text_changed()
{
  const auto text = m_searchentry-&gt;get_text();
  auto tab = dynamic_cast&lt;Gtk::ScrolledWindow*&gt;(m_stack-&gt;get_visible_child());
  auto view = dynamic_cast&lt;Gtk::TextView*&gt;(tab-&gt;get_child());

  // Very simple-minded search implementation.
  auto buffer = view-&gt;get_buffer();
  Gtk::TextIter match_start;
  Gtk::TextIter match_end;
  if (buffer-&gt;begin().forward_search(text, Gtk::TextSearchFlags::CASE_INSENSITIVE,
      match_start, match_end))
  {
    buffer-&gt;select_range(match_start, match_end);
    view-&gt;scroll_to(match_start);
  }
}

void ExampleWindow::on_printoperation_done(Gtk::PrintOperationResult result,
  const Glib::RefPtr&lt;PrintOperation&gt;&amp; op)
{
  if (result == Gtk::PrintOperation::Result::ERROR)
    //notify user
  else if (result == Gtk::PrintOperation::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;PrintOperation&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 gtk_widget_set_device_events(GtkWidget* widget, GdkDevice* device,
  GdkEventMask events);

void init()
{
  Gtk::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;

int 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_button_clicked(const Glib::ustring&amp; data);

void on_insert(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#! /bin/sh -e
test -n "$srcdir" || srcdir=`dirname "$0"`
test -n "$srcdir" || srcdir=.

autoreconf --force --install --verbose --warnings=all "$srcdir"
echo "Running intltoolize --copy --force --automake"
intltoolize --copy --force --automake
test -n "$NOCONFIGURE" || "$srcdir/configure" "$@"#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)')$ cp examples/sample.jhbuildrc ~/.config/jhbuildrc$ glib-compile-resources --target=resources.c --generate-source exampleapp.gresource.xml$ glib-compile-resources --target=resources.c --generate-source image.gresource.xml$ glib-compile-resources --target=resources.c --generate-source toolbar.gresource.xml$ jhbuild bootstrap
$ jhbuild sanitycheck(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];<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>cairo</application><application>cairomm-1.16</application><application>gdk-pixbuf-2.0</application><application>glib-2.0</application><application>glibmm-2.68</application><application>graphene-1.0</application><application>gtk4</application><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.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> 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> 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> 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 cuatro tipos básicos de botones:<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>, 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>gestor de señales</emphasis> para atrapar la señal «clicked» del botón.<application>pango</application><application>pangomm-2.48</application><application>pkg-config</application><application>sigc++-3.0</application><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>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>, <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::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::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::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::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 widgets <classname>Range</classname> típicamente conectan un gestor 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>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.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>.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>:<filename>/toolbar/rain.png</filename><filename>/toolbar/toolbar.glade</filename><filename>gtk.defs</filename><filename>gtk_enums.defs</filename><filename>gtk_vfuncs.defs</filename><filename>libsomething</filename>: contiene el archivo de cabecera principal y el archivo .pc de pkg-config.<filename>libsomethingmm</filename>: la carpeta de nivel superior.<filename>skeleton/skeletonmm/meson.build</filename><filename>src</filename>: contiene los archivos de fuentes .hg y .ccg.<firstname>Murray</firstname> <surname>Cumming</surname><function>_CLASS_BOXEDTYPE( C++ class, C class, new function, copy function, free function )</function><function>_CLASS_BOXEDTYPE_STATIC( C++ class, C class )</function><function>_CLASS_GENERIC( C++ class, C class )</function><function>_CLASS_GOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )</function><function>_CLASS_GTKOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )</function><function>_CLASS_GTKOBJECT()</function><function>_CLASS_INTERFACE( C++ class, C class, C casting macro, C interface struct, Base C++ class (optional), Base C class (optional) )</function><function>_CLASS_OPAQUE_COPYABLE( C++ class, C class, new function, copy function, free function )</function><function>_CLASS_OPAQUE_REFCOUNTED( C++ class, C class, new function, ref function, unref function )</function><function>_CTOR_DEFAULT</function><function>_DEFS()</function><function>_IGNORE(C function name 1, C function name 2, etc)
_IGNORE_SIGNAL(C signal name 1, C signal name 2, etc)
_IGNORE_PROPERTY(C property name 1, C property name 2, etc)</function><function>_IMPLEMENTS_INTERFACE()</function><function>_IMPLEMENTS_INTERFACE(C++ interface name)</function><function>_MEMBER_GET(C++ name, C name, C++ type, C type)</function><function>_MEMBER_GET_GOBJECT(C++ name, C name, C++ type, C type)</function><function>_MEMBER_GET_PTR(C++ name, C name, C++ type, C type)</function><function>_MEMBER_SET(C++ name, C name, C++ type, C type)</function><function>_MEMBER_SET_GOBJECT(C++ name, C name, C++ type, C type)</function><function>_MEMBER_SET_PTR(C++ name, C name, C++ type, C type)</function><function>_PINCLUDE()</function><function>_WRAP_METHOD()</function>, <function>_WRAP_SIGNAL()</function>, y <function>_WRAP_PROPERTY()</function><function>_WRAP_PROPERTY(C property name, C++ type)</function><function>_WRAP_SIGNAL( C++ signal handler signature, C signal name)</function><function>_WRAP_VFUNC( C++ method signature, C function name)</function><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>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>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_delete</literal>: le da al origen la oportunidad de eliminar los datos originales si es lo apropiado.<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 gestor <literal>begin_print</literal>.<literal>end_print</literal>: su gestor 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_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>upper</literal>: valor máximo del rango<literal>value</literal>: valor del «SpinButton»<methodname>drag_dest_add_text_targets()</methodname><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>on_map()</methodname>: (opcional)<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)<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.<type>bool</type><type>double</type><type>gboolean</type><type>gchar*</type><type>gdouble</type><type>gint</type><type>guint</type><type>gunichar</type><type>int</type><ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1RefPtr.html">Referencia</ulink><ulink url="http://developer.gnome.org/glibmm/unstable/namespaceGlib.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGdk_1_1Clipboard.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1AboutDialog.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1AspectFrame.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Assistant.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Box.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Builder.html">Referencia</ulink><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_1Button.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1CheckButton.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ColorChooserDialog.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ComboBox.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Dialog.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Entry.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1EntryCompletion.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1FileChooserDialog.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1FontChooserDialog.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Frame.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Grid.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1InfoBar.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Label.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ListStore.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1MessageDialog.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Notebook.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1PageSetup.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Paned.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1PrintOperation.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ProgressBar.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1RadioButton.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Range.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Scale.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Scrollbar.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ScrolledWindow.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1SpinButton.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextBuffer.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextChildAnchor.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextIter.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextMark.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextTag.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextTagTable.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextView.html">Referencia</ulink><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>.<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToggleButton.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Tooltip.html">Tooltip >Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeModel.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeStore.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeView.html">Referencia</ulink><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Widget.html">Widget >Referencia</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/aspectframe">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/assistant/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/base">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/box">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step1">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step2">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step3">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step4">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step5">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step6">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step7">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step8">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buildapp/step9">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/builder/basic">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buttons/button">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buttons/checkbutton">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/buttons/radiobutton">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/clipboard/ideal/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/clipboard/simple/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/combobox/complex">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/combobox/entry_complex">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/combobox/entry_text">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/combobox/text">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/custom/custom_container/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/custom/custom_widget/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/aboutdialog">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/colorchooserdialog">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/filechooserdialog">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/fontchooserdialog">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/dialogs/messagedialog">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/arcs">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/clock">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/curve">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/image">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/pango_text">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/simple">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/drawingarea/thin_lines">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/entry/completion">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/entry/icon">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/entry/progress">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/entry/simple">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/frame">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/grid">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/helloworld2">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/idle/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/infobar">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/input/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/keyboard_events/propagation/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/keyboard_events/simple/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/label">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/menus/main_menu/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/menus/popup/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/menus_and_toolbars">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/multithread">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/notebook/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/paned">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/printing/simple/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/progressbar">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/range_widgets">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/recent_files">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/scrolledwindow">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/signals/custom/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/spinbutton">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/textview/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/timeout/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/tooltips">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/drag_and_drop/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/editable_cells/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/list/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/popup/">Código fuente</ulink><ulink url="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/treeview/tree/">Código fuente</ulink><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>defs_basefiles</varname><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>extra_cc_files, extra_h_files</varname><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>hg_ccg_basenames</varname><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 recurso<year>2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010</year> <holder>Murray Cumming</holder>Un <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 <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.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 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.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.AM_CPPFLAGS = ... -DPROGRAMNAME_LOCALEDIR=\"${PROGRAMNAME_LOCALEDIR}\"AboutDialogAcceso a widgetsAccionesModo de actividadAñada <literal>po</literal> a la variable <literal>SUBDIRS</literal>. Sin esto, las traducciones no se construirán al construir el programa.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 widgetsAdemá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 ajusteAjustesDespué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 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 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.Todos 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.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.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 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.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.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» mejoradoOtra 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 gestores de señales.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.Tiempo de vida de la aplicaciónAplicar etiquetasComo 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 gestores de señales a la señal <literal>value_changed</literal> de sus ajustes, como también puede su programa.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.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.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.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>.Ademá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 2CajasBotónBotonesDe 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.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.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++CONV_TO_INTCairo y PangoConversión de tiposCambios 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ónCasilla de verificaciónLos 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>.Widgets 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 gestores apropiados.Conectar gestores 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 constructoresWidgets 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 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 gestores 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ñalesActualmente, <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-cacheDeclare 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 predeterminadoDependeciasEliminar 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.Distintos tipos de uniones en CairoDesconectar gestores de señalesHace 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.DocumentaciónEstructura de construcción de la documentaciónArrastrar y soltarDibujar 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 relativasAsignación dinámica con new y deleteCada <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.Celdas editablesEntryCompletado 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 gestor de eventos, se llamará.EjemploAplicación de ejemplo: crear un reloj con CairoEjemplosExcepciones en gestores de señalesEsperar UTF8Exportar a PDFExtender el diálogo de impresiónSelector de archivosFileChooserDialogFontChooserDialogPara un CellRendererToggle, establecería la propiedad <emphasis>activable</emphasis> en su lugar.Por ejemplo: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, para un CellRendererText, establecería la propiedad <emphasis>editable</emphasis> de la celda a «true», así:Por ejemplo, este código podría ser problemático: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 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.MarcoEjemplo completoWidgets de alcance de funciónGLib::ustring text(C_("noun", "jumps"));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 propiedadesObtenga los datos de los widgets en el gestor de señales <literal>custom_widget_apply</literal>.Obtener ayuda con las traduccionesObtener los valoresGlade 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::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::ustringGlib::ustring y std::iostreamsGridGruposGtk::Application y opciones de línea de comandosGtk::Box(Gtk::Orientation orientation = Gtk::Orientation::HORIZONTAL, int spacing = 0);
void set_orientation(Gtk::Orientation orientation);
void set_spacing(int spacing);
void set_homogeneous(bool homogeneous = true);Gtk::Button* pButton = new Gtk::Button("_Something", true);Gtk::ComboBox ahora deriva de CellLayout, permitiendo una disposición y alineación más fácil de sus <classname>Gtk::CellRenderer</classname>.Gtk::IconTheme::get_for_display(get_display())-&gt;add_resource_path("/org/gtkmm/exampleapp");
set_icon_name("exampleapp");

Gtk::TreeModel::Children children = row.children();Gtk::TreeModel::iterator iter = m_Combo.get_active();
if(iter)
{
  auto row = *iter;

  //Get the data for the selected row, using our knowledge
  //of the tree model:
  auto id = row[m_Columns.m_col_id];
  set_something_id_chosen(id); //Your own function.
}
else
  set_nothing_chosen(); //Your own function.Gtk::Window window;
window.set_default_size(200, 200);Archivos de código fuente programados a manoEscribir constructores a manoManejar <literal>button_press_event</literal>Barra de cabeceraCabeceras y enlazadoHello WorldHola mundo 2«Hola mundo» en <application>gtkmm</application>HelloWorld::HelloWorld()
: m_button("Hello World")
{
  m_button.set_margin(10);
  m_button.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;HelloWorld::on_button_clicked));
  set_child(m_button);
}Algunos ejemplos de gestión normal de la memoria en C++:Aquí 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 gestor 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í 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.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 gestor 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:Cómo funciona gettextSin 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>.INTLTOOL_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_GNU_GETTEXT([external])
AM_GNU_GETTEXT_VERSION([0.17])

PROGRAMNAME_LOCALEDIR=[${datadir}/locale]
AC_SUBST(PROGRAMNAME_LOCALEDIR)IdealFunciones 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 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 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 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 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 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.Implementación de la lógica personalizada para celdas editables.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 gestor predeterminado (<methodname>on_key_release_event()</methodname>), y otro gestor 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 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 gestores de eventos que se llaman después del gestor 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 gestor de eventos predeterminado se sobrecarga, como se describe en la sección <link linkend="sec-overriding-default-signal-handlers">Sobrecargar los gestores 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 gestor 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 modeloInfoBarInicializació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 gestores 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 gestor de señales predeterminado, como Button::on_clicked(). Esto puede ser mucho más simple que enganchar gestores de señales para todo.Internacionalización y localizaciónIntroducciónEs 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: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 modeloIteradoresSó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: simpleEtiquetaFalta de propiedadesSe 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 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ú principalWidgets 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 traducirMarcasTal 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.Gestión de la memoriaMenús y barras de herramientasMessageDialogMacros de métodosMétodosMicrosoft WindowsWidgets variosMezclando las API de C y C++Columnas del modeloModificar archivos de construcciónModificar la lista de archivos recientesMonitorizar E/SMás de una columna del modelo por columna de la vistaLa 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>.MoverPrograma con múltiples hilosProgramas con múltiples hilosNO_GTYPENicolai M. Josuttis, «The C++ Standard Library» - sección 4.2AboutDialog no modalGestión normal de la memoria en C++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, 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 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, 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, 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 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 gestores 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.Hasta aquí está todo bien, pero ¿y si quiere crear sus propios gestores 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 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>.En Unix, el gestor 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.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.Procesado de parámetros opcionalesOtras 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>.Todos los ejemplos tienden a tener la misma estructura. Siguen estos pasos para usar un <classname>widget</classname>:Procesado de parámetros de salidaReemplazar gestores de señales predeterminadosVista generalPKG_CHECK_MODULES([MYAPP], [gtkmm-4.0 &gt;= 4.8.0])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).Reordenación de parámetrosPegarOpciones 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 comunesMenú 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 simpleProblemas en la API de C.Las 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.ProgressBarPone 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 RangoLas 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.RecentManagerDocumentos usados recientementeTécnicas recomendadasRecuerde 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 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 CFila hijaMismas cadenas, semánticas diferentesWidgets de EscalaWidgets de barras de desplazamientoScrolledWindowDesplazamientoConsulte <link linkend="sec-printing-example-simple">un ejemplo</link> de cómo realizar esto exactamente. 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».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 gestor 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 compartidosSecuencia de los gestores 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 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 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.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 gestor de señales de esta forma: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).OrdenarOrdenación al pulsar en columnasOrí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 CellRendererSpinButtonLas 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 gestores 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 gestor separado. Esto es aún más cierto si quiere que varios objetos manejen la misma señal, o si quiere que un gestor de señales responda a la misma señal desde diferentes objetos.TagTableEtiquetasEtiquetas y formateadoLe 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»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.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>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.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::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.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.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>.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 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 búferLa 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 gestor <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 modeloEl puntero inteligente RefPtrLa selecciónEl widget TreeViewLa 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.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 compilador le hará saber si usa un tipo inapropiado. Por ejemplo, esto generaría un error de compilación:Las limitacionesLa entradaEl evento se entrega primero al widget en el que ocurrió. Si todos los gestores 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 gestor 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.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>:La primera llamada a <methodname>connect()</methodname> es igual a la que vio la última vez; no hay nada nuevo aquí.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 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 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>.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.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í: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>.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.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 gestores 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.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 gestor 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 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 gestor de señales es <methodname>on_button_clicked()</methodname>.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.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>.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>.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.Luego, para añadir un widget en esa posición, use <methodname>Gtk::TextView::add_child_at_anchor()</methodname>: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 muchos más contenedores, de los que también se hablará.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 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.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 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 gestor 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 gestor de señales. Si el valor es <literal>true</literal>, entonces no se necesitará llamar a ningún otro gestor de señales.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 gestores 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 gestor de señales: llamando a <methodname>disconnect()</methodname> en el objeto <classname>sigc::connection</classname>, o devolviendo <literal>false</literal> en el gestor 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>.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 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 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 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 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 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 involucra una variedad de herramientas, algunas de ellas obsoletas, pero que al menos funcionan, y que varios proyectos han usado exitosamente.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.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 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 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>.Tiempos de esperaTiempos de espera, E/S y funciones en esperaPara 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 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 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 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 descubrir qué filas ha seleccionado el usuario, obtenga el objeto <classname>Gtk::TreeView::Selection</classname> del <classname>TreeView</classname>, así:Para descubrir qué tipo de gestor 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 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 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 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 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:Botones conmutablesBotón ConmutableConsejoConsejosTreeStoreTreeStore, 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í:Los cambios en la IU pueden observarse más rápidamente, por lo se pueden mejorar las IU.No se pueden predeclarar estructurasUnix y LinuxA 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.Palabras poco frecuentesUse <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 <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 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>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 gestor de señales se esperará que conecte a una señal dada.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.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 gestor de señales a la señal <literal>clicked</literal> de <literal>m_button</literal>. Esto imprime nuestro amigable saludo a <literal>stdout</literal>.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>.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 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 gestor de señales lanzó la excepción.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 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 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 gestor de eventos establecido para que se llame antes, y ese es el que se llama primero (<methodname>windowKeyReleaseBefore()</methodname>). Después se llama al gestor 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 gestores 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 gestor de señales para manejar tales eventos.Widget::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 y ChildAnchorsCon 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 bibliotecas C con gmmprocEscribir gestores 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.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 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 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 gestor de señales. Por lo tanto, si quiere que su método se llame repetidamente, debe devolver <literal>true</literal>.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 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 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>.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.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.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 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 establecer el parámetro opcional <literal>after = false</literal> en la llamada a <literal>signal_command_line().connect()</literal>, porque su gestor de señales debe llamarse antes que el gestor 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>).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 gestor 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.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.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>.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>._CLASS_BOXEDTYPE_CLASS_BOXEDTYPE_STATIC_CLASS_GENERIC_CLASS_GOBJECT_CLASS_GTKOBJECT_CLASS_INTERFACE_CLASS_OPAQUE_COPYABLE_CLASS_OPAQUE_REFCOUNTED_CTOR_DEFAULT_CUSTOM_CTOR_CAST_CUSTOM_DTOR_CUSTOM_MOVE_OPERATIONS_CUSTOM_WRAP_FUNCTION_CUSTOM_WRAP_NEW_IGNORE, _IGNORE_SIGNAL, _IGNORE_PROPERTY_IMPLEMENTS_INTERFACE_MEMBER_GET / _MEMBER_SET_MEMBER_GET(x, x, int, int)_MEMBER_GET_GOBJECT / _MEMBER_SET_GOBJECT_MEMBER_GET_PTR / _MEMBER_SET_PTR_NO_WRAP_FUNCTION_WRAP_CTOR_WRAP_ENUM_WRAP_ENUM_DOCS_ONLY_WRAP_GERROR_WRAP_METHOD_WRAP_METHOD_DOCS_ONLY_WRAP_PROPERTY_WRAP_SIGNAL_WRAP_VFUNCadd_action(Gio::PropertyAction::create("show-lines", m_lines-&gt;property_visible()));
m_binding_lines_visible = Glib::Binding::bind_property(m_lines-&gt;property_visible(),
  m_lines_label-&gt;property_visible());

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 luegoauto app = Gtk::Application::create("org.gtkmm.examples.base");auto cols_count = m_TreeView.append_column_editable("Alex", m_columns.alex);
auto pColumn = m_TreeView.get_column(cols_count-1);
if(pColumn)
{
  auto 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);auto entry = m_Combo.get_entry();
if (entry)
{
  // 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) );
}auto iter = m_refListStore-&gt;append();auto iter = m_refModel-&gt;children().begin()
if(iter)
  refTreeSelection-&gt;select(iter);auto iter = refTreeSelection-&gt;get_selected();
if(iter) //If anything is selected
{
  auto row = *iter;
  //Do something with the row.
}auto iter_child =
    m_refTreeStore-&gt;append(row.children());auto pColumn = treeview.get_column(0);
if(pColumn)
  pColumn-&gt;set_sort_column(m_columns.m_col_id);auto refTagMatch = Gtk::TextBuffer::Tag::create();
refTagMatch-&gt;property_background() = "orange";auto 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.
auto refBuffer = Gtk::TextBuffer::create(refTagTable);auto row = *iter;auto row = m_refModel-&gt;children()[5]; //The sixth row.
if(row)
  refTreeSelection-&gt;select(row.get_iter());auto sorted_model = Gtk::TreeModelSort::create(model);
sorted_model-&gt;set_sort_column(columns.m_col_name, Gtk::SORT_ASCENDING);
treeview.set_model(sorted_model);auto strText = row[m_Columns.m_col_text];
auto number = row[m_Columns.m_col_number];bindtextdomain(GETTEXT_PACKAGE, PROGRAMNAME_LOCALEDIR);
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
textdomain(GETTEXT_PACKAGE);bool DemoWindow::select_function(
    const Glib::RefPtr&lt;Gtk::TreeModel&gt;&amp; model,
    const Gtk::TreeModel::Path&amp; path, bool)
{
  const auto iter = model-&gt;get_iter(path);
  return iter-&gt;children().empty(); // only allow leaf nodes to be selected
}ejemplo de botonesclass HelloWorld : public Gtk::Window
{
public:
  HelloWorld();
  ~HelloWorld() override;

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

  //Member widgets:
  Gtk::Button m_button;
};class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
  ModelColumns()
  { 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;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;constversioncontext-&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_callbackdeprecated ["&lt;text&gt;"]desktopdir = $(datadir)/applications
desktop_in_files = programname.desktop.in
desktop_DATA = $(desktop_in_files:.desktop.in=.desktop)
@INTLTOOL_DESKTOP_RULE@detail_name &lt;parameter_name&gt;display_message("Getting ready for i18n.");display_message(_("Getting ready for i18n."));enumserr_return_value &lt;value&gt;errthrowerrthrow ["&lt;exceptions&gt;"]exception_handler &lt;method_name&gt;funcionesg++ simple.cc -o simple `pkg-config gtkmm-4.0 --cflags --libs`Procesado de parámetros de gmmprocgtkmmifdef &lt;identifier&gt;int main(int argc, char* argv[])
{
  auto app = Gtk::Application::create("org.gtkmm.example");
  HelloWorld helloworld;
  return app-&gt;run(helloworld, argc, argv);
}intltool-update --potkeep_returnConversiones 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.append(m_Button1);
m_box.append(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.set_child(m_box);m_refTreeSelection-&gt;set_select_function( sigc::mem_fun(*this,
    &amp;DemoWindow::select_function) );modules = [ 'gtkmm' ]newin "&lt;version&gt;"no_default_handlerno_slot_copyobjetos (GObjects, widgets, interfaces, tipos en caja y estructuras planas)opropiedadesrefBuffer-&gt;apply_tag(refTagMatch, iterRangeStart, iterRangeStop);refBuffer-&gt;insert_with_tag(iter, "Some text", refTagMatch);refTreeSelection-&gt;selected_foreach_iter(
    sigc::mem_fun(*this, &amp;TheClass::selected_row_callback) );

void TheClass::selected_row_callback(
    const Gtk::TreeModel::const_iterator&amp; iter)
{
  auto 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_ctypereturn app-&gt;run(window, argc, argv);return_value &lt;value&gt;row[m_Columns.m_col_text] = "sometext";s#&lt;from&gt;#&lt;to&gt;#señalesslot_callback &lt;function_name&gt;slot_name &lt;parameter_name&gt;src/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::locale::global(std::locale("")); // Set the global locale to the user's preferred locale.
                                      // Usually unnecessary here, because Glib::init()
                                      // or Gtk::Application::create() does it for you.
std::ostringstream output;
output &lt;&lt; percentage &lt;&lt; " % done";
label-&gt;set_text(Glib::locale_to_utf8(output.str()));«vfuncs»«vfuncs» (campos miembro de punteros de funciones en estructuras), escritas a mano.void ExampleWindow::on_button_copy()
{
  get_clipboard()-&gt;set_text("example_custom_target");
}void ExampleWindow::on_button_delete()
{
  auto refTreeSelection = m_treeview.get_selection();
  if(refTreeSelection)
  {
    auto sorted_iter = m_refTreeSelection-&gt;get_selected();
    if(sorted_iter)
    {
      auto iter = m_refModelSort-&gt;convert_iter_to_child_iter(sorted_iter);
      m_refModel-&gt;erase(iter);
    }
  }
}void ExampleWindow::on_button_paste()
{
  get_clipboard()-&gt;read_text_async(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_clipboard_received));
}void ExampleWindow::on_clipboard_received(Glib::RefPtr&lt;Gio::AsyncResult&gt;&amp; result)
{
  auto text = get_clipboard()-&gt;read_text_finish(result);
  //Do something with the pasted data.
}void MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr, int width, int height)
{
  auto 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();
}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();
}voidreturndonde <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).xgettext -a -o my-strings --omit-header *.cc *.h