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
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000;
/*!
\class QGraphicsScene
\brief The QGraphicsScene class provides a surface for managing a large
number of 2D graphical items.
\since 4.2
\ingroup multimedia
\ingroup graphicsview-api
\mainclass
The class serves as a container for QGraphicsItems. It is used together
with QGraphicsView for visualizing graphical items, such as lines,
rectangles, text, or even custom items, on a 2D surface. QGraphicsScene is
part of \l{The Graphics View Framework}.
QGraphicsScene also provides functionality that lets you efficiently
determine both the location of items, and for determining what items are
visible within an arbitrary area on the scene. With the QGraphicsView
widget, you can either visualize the whole scene, or zoom in and view only
parts of the scene.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 0
Note that QGraphicsScene has no visual appearance of its own; it only
manages the items. You need to create a QGraphicsView widget to visualize
the scene.
To add items to a scene, you start off by constructing a QGraphicsScene
object. Then, you have two options: either add your existing QGraphicsItem
objects by calling addItem(), or you can call one of the convenience
functions addEllipse(), addLine(), addPath(), addPixmap(), addPolygon(),
addRect(), or addText(), which all return a pointer to the newly added item.
The dimensions of the items added with these functions are relative to the
item's coordinate system, and the items position is initialized to (0,
0) in the scene.
You can then visualize the scene using QGraphicsView. When the scene
changes, (e.g., when an item moves or is transformed) QGraphicsScene
emits the changed() signal. To remove an item, call removeItem().
QGraphicsScene uses an indexing algorithm to manage the location of items
efficiently. By default, a BSP (Binary Space Partitioning) tree is used; an
algorithm suitable for large scenes where most items remain static (i.e.,
do not move around). You can choose to disable this index by calling
setItemIndexMethod(). For more information about the available indexing
algorithms, see the itemIndexMethod property.
The scene's bounding rect is set by calling setSceneRect(). Items can be
placed at any position on the scene, and the size of the scene is by
default unlimited. The scene rect is used only for internal bookkeeping,
maintaining the scene's item index. If the scene rect is unset,
QGraphicsScene will use the bounding area of all items, as returned by
itemsBoundingRect(), as the scene rect. However, itemsBoundingRect() is a
relatively time consuming function, as it operates by collecting
positional information for every item on the scene. Because of this, you
should always set the scene rect when operating on large scenes.
One of QGraphicsScene's greatest strengths is its ability to efficiently
determine the location of items. Even with millions of items on the scene,
the items() functions can determine the location of an item within few
milliseconds. There are several overloads to items(): one that finds items
at a certain position, one that finds items inside or intersecting with a
polygon or a rectangle, and more. The list of returned items is sorted by
stacking order, with the topmost item being the first item in the list.
For convenience, there is also an itemAt() function that returns the
topmost item at a given position.
QGraphicsScene maintains selection information for the scene. To select
items, call setSelectionArea(), and to clear the current selection, call
clearSelection(). Call selectedItems() to get the list of all selected
items.
\section1 Event Handling and Propagation
Another responsibility that QGraphicsScene has, is to propagate events
from QGraphicsView. To send an event to a scene, you construct an event
that inherits QEvent, and then send it using, for example,
QApplication::sendEvent(). event() is responsible for dispatching
the event to the individual items. Some common events are handled by
convenience event handlers. For example, key press events are handled by
keyPressEvent(), and mouse press events are handled by mousePressEvent().
Key events are delivered to the \e {focus item}. To set the focus item,
you can either call setFocusItem(), passing an item that accepts focus, or
the item itself can call QGraphicsItem::setFocus(). Call focusItem() to
get the current focus item. For compatibility with widgets, the scene also
maintains its own focus information. By default, the scene does not have
focus, and all key events are discarded. If setFocus() is called, or if an
item on the scene gains focus, the scene automatically gains focus. If the
scene has focus, hasFocus() will return true, and key events will be
forwarded to the focus item, if any. If the scene loses focus, (i.e.,
someone calls clearFocus(),) while an item has focus, the scene will
maintain its item focus information, and once the scene regains focus, it
will make sure the last focus item regains focus.
For mouse-over effects, QGraphicsScene dispatches \e {hover
events}. If an item accepts hover events (see
QGraphicsItem::acceptHoverEvents()), it will receive a \l
{QEvent::}{GraphicsSceneHoverEnter} event when the mouse enters
its area. As the mouse continues moving inside the item's area,
QGraphicsScene will send it \l {QEvent::}{GraphicsSceneHoverMove}
events. When the mouse leaves the item's area, the item will
receive a \l {QEvent::}{GraphicsSceneHoverLeave} event.
All mouse events are delivered to the current \e {mouse grabber}
item. An item becomes the scene's mouse grabber if it accepts
mouse events (see QGraphicsItem::acceptedMouseButtons()) and it
receives a mouse press. It stays the mouse grabber until it
receives a mouse release when no other mouse buttons are
pressed. You can call mouseGrabberItem() to determine what item is
currently grabbing the mouse.
\sa QGraphicsItem, QGraphicsView
*/
/*!
\enum QGraphicsScene::SceneLayer
\since 4.3
This enum describes the rendering layers in a QGraphicsScene. When
QGraphicsScene draws the scene contents, it renders each of these layers
separately, in order.
Each layer represents a flag that can be OR'ed together when calling
functions such as invalidate() or QGraphicsView::invalidateScene().
\value ItemLayer The item layer. QGraphicsScene renders all items are in
this layer by calling the virtual function drawItems(). The item layer is
drawn after the background layer, but before the foreground layer.
\value BackgroundLayer The background layer. QGraphicsScene renders the
scene's background in this layer by calling the virtual function
drawBackground(). The background layer is drawn first of all layers.
\value ForegroundLayer The foreground layer. QGraphicsScene renders the
scene's foreground in this layer by calling the virtual function
drawForeground(). The foreground layer is drawn last of all layers.
\value AllLayers All layers; this value represents a combination of all
three layers.
\sa invalidate(), QGraphicsView::invalidateScene()
*/
/*!
\enum QGraphicsScene::ItemIndexMethod
This enum describes the indexing algorithms QGraphicsScene provides for
managing positional information about items on the scene.
\value BspTreeIndex A Binary Space Partitioning tree is applied. All
QGraphicsScene's item location algorithms are of an order close to
logarithmic complexity, by making use of binary search. Adding, moving and
removing items is logarithmic. This approach is best for static scenes
(i.e., scenes where most items do not move).
\value NoIndex No index is applied. Item location is of linear complexity,
as all items on the scene are searched. Adding, moving and removing items,
however, is done in constant time. This approach is ideal for dynamic
scenes, where many items are added, moved or removed continuously.
\sa setItemIndexMethod(), bspTreeDepth
*/
#include "qgraphicsscene.h"
#ifndef QT_NO_GRAPHICSVIEW
#include "qgraphicsitem.h"
#include "qgraphicsitem_p.h"
#include "qgraphicslayout.h"
#include "qgraphicsscene_p.h"
#include "qgraphicssceneevent.h"
#include "qgraphicsview.h"
#include "qgraphicsview_p.h"
#include "qgraphicswidget.h"
#include "qgraphicswidget_p.h"
#include <QtCore/qdebug.h>
#include <QtCore/qlist.h>
#include <QtCore/qmath.h>
#include <QtCore/qrect.h>
#include <QtCore/qset.h>
#include <QtCore/qstack.h>
#include <QtCore/qtimer.h>
#include <QtCore/qvarlengtharray.h>
#include <QtGui/qapplication.h>
#include <QtGui/qdesktopwidget.h>
#include <QtGui/qevent.h>
#include <QtGui/qgraphicslayout.h>
#include <QtGui/qgraphicsproxywidget.h>
#include <QtGui/qgraphicswidget.h>
#include <QtGui/qmatrix.h>
#include <QtGui/qpaintengine.h>
#include <QtGui/qpainter.h>
#include <QtGui/qpixmapcache.h>
#include <QtGui/qpolygon.h>
#include <QtGui/qstyleoption.h>
#include <QtGui/qtooltip.h>
#include <QtGui/qtransform.h>
#include <private/qapplication_p.h>
#include <private/qobject_p.h>
#ifdef Q_WS_X11
#include <private/qt_x11_p.h>
#endif
QT_BEGIN_NAMESPACE
static inline bool QRectF_intersects(const QRectF &s, const QRectF &r)
{
qreal xp = s.left();
qreal yp = s.top();
qreal w = s.width();
qreal h = s.height();
qreal l1 = xp;
qreal r1 = xp;
if (w < 0)
l1 += w;
else
r1 += w;
qreal l2 = r.left();
qreal r2 = r.left();
if (w < 0)
l2 += r.width();
else
r2 += r.width();
if (l1 >= r2 || l2 >= r1)
return false;
qreal t1 = yp;
qreal b1 = yp;
if (h < 0)
t1 += h;
else
b1 += h;
qreal t2 = r.top();
qreal b2 = r.top();
if (r.height() < 0)
t2 += r.height();
else
b2 += r.height();
return !(t1 >= b2 || t2 >= b1);
}
// QRectF::intersects() returns false always if either the source or target
// rectangle's width or height are 0. This works around that problem.
static inline void _q_adjustRect(QRectF *rect)
{
Q_ASSERT(rect);
if (!rect->width())
rect->adjust(-0.00001, 0, 0.00001, 0);
if (!rect->height())
rect->adjust(0, -0.00001, 0, 0.00001);
}
static inline QRectF adjustedItemBoundingRect(const QGraphicsItem *item)
{
Q_ASSERT(item);
QRectF boundingRect(item->boundingRect());
_q_adjustRect(&boundingRect);
return boundingRect;
}
static void _q_hoverFromMouseEvent(QGraphicsSceneHoverEvent *hover, const QGraphicsSceneMouseEvent *mouseEvent)
{
hover->setWidget(mouseEvent->widget());
hover->setPos(mouseEvent->pos());
hover->setScenePos(mouseEvent->scenePos());
hover->setScreenPos(mouseEvent->screenPos());
hover->setLastPos(mouseEvent->lastPos());
hover->setLastScenePos(mouseEvent->lastScenePos());
hover->setLastScreenPos(mouseEvent->lastScreenPos());
hover->setModifiers(mouseEvent->modifiers());
hover->setAccepted(mouseEvent->isAccepted());
}
/*!
\internal
*/
QGraphicsScenePrivate::QGraphicsScenePrivate()
: changedSignalMask(0),
indexMethod(QGraphicsScene::BspTreeIndex),
bspTreeDepth(0),
lastItemCount(0),
hasSceneRect(false),
updateAll(false),
calledEmitUpdated(false),
selectionChanging(0),
dirtyItemResetPending(false),
regenerateIndex(true),
purgePending(false),
indexTimerId(0),
restartIndexTimer(false),
stickyFocus(false),
hasFocus(false),
focusItem(0),
lastFocusItem(0),
tabFocusFirst(0),
activeWindow(0),
activationRefCount(0),
lastMouseGrabberItem(0),
lastMouseGrabberItemHasImplicitMouseGrab(false),
dragDropItem(0),
enterWidget(0),
lastDropAction(Qt::IgnoreAction),
painterStateProtection(true),
sortCacheEnabled(false),
updatingSortCache(false),
style(0)
{
}
/*!
\internal
*/
void QGraphicsScenePrivate::init()
{
Q_Q(QGraphicsScene);
// Keep this index so we can check for connected slots later on.
changedSignalMask = (1 << q->metaObject()->indexOfSignal("changed(QList<QRectF>)"));
qApp->d_func()->scene_list.append(q);
q->update();
}
/*!
\internal
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::estimateItemsInRect(const QRectF &rect) const
{
const_cast<QGraphicsScenePrivate *>(this)->purgeRemovedItems();
const_cast<QGraphicsScenePrivate *>(this)->_q_updateSortCache();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
// ### Only do this once in a while.
QGraphicsScenePrivate *that = const_cast<QGraphicsScenePrivate *>(this);
// Get items from BSP tree
QList<QGraphicsItem *> items = that->bspTree.items(rect);
// Fill in with any unindexed items
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (!item->d_ptr->itemDiscovered && item->d_ptr->visible && !(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
QRectF boundingRect = item->sceneBoundingRect();
if (QRectF_intersects(boundingRect, rect)) {
item->d_ptr->itemDiscovered = 1;
items << item;
}
}
}
}
// Reset the discovered state of all discovered items
for (int i = 0; i < items.size(); ++i)
items.at(i)->d_func()->itemDiscovered = 0;
return items;
}
QList<QGraphicsItem *> itemsInRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0))
itemsInRect << item;
}
}
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0))
itemsInRect << item;
}
}
return itemsInRect;
}
/*!
\internal
*/
void QGraphicsScenePrivate::addToIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
if (item->d_func()->index != -1) {
bspTree.insertItem(item, item->sceneBoundingRect());
foreach (QGraphicsItem *child, item->children())
child->addToIndex();
} else {
// The BSP tree is regenerated if the number of items grows to a
// certain threshold, or if the bounding rect of the graph doubles in
// size.
startIndexTimer();
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeFromIndex(QGraphicsItem *item)
{
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int index = item->d_func()->index;
if (index != -1) {
bspTree.removeItem(item, item->sceneBoundingRect());
freeItemIndexes << index;
indexedItems[index] = 0;
item->d_func()->index = -1;
unindexedItems << item;
foreach (QGraphicsItem *child, item->children())
child->removeFromIndex();
}
startIndexTimer();
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::resetIndex()
{
purgeRemovedItems();
if (indexMethod == QGraphicsScene::BspTreeIndex) {
for (int i = 0; i < indexedItems.size(); ++i) {
if (QGraphicsItem *item = indexedItems.at(i)) {
item->d_ptr->index = -1;
unindexedItems << item;
}
}
indexedItems.clear();
freeItemIndexes.clear();
regenerateIndex = true;
startIndexTimer();
}
}
static inline int intmaxlog(int n)
{
return (n > 0 ? qMax(qCeil(qLn(qreal(n)) / qLn(qreal(2))), 5) : 0);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_updateIndex()
{
if (!indexTimerId)
return;
Q_Q(QGraphicsScene);
q->killTimer(indexTimerId);
indexTimerId = 0;
purgeRemovedItems();
// Add unindexedItems to indexedItems
QRectF unindexedItemsBoundingRect;
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
unindexedItemsBoundingRect |= item->sceneBoundingRect();
if (!freeItemIndexes.isEmpty()) {
int freeIndex = freeItemIndexes.takeFirst();
item->d_func()->index = freeIndex;
indexedItems[freeIndex] = item;
} else {
item->d_func()->index = indexedItems.size();
indexedItems << item;
}
}
}
// Update growing scene rect.
QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
growingItemsBoundingRect |= unindexedItemsBoundingRect;
// Determine whether we should regenerate the BSP tree.
if (indexMethod == QGraphicsScene::BspTreeIndex) {
int depth = bspTreeDepth;
if (depth == 0) {
int oldDepth = intmaxlog(lastItemCount);
depth = intmaxlog(indexedItems.size());
static const int slack = 100;
if (bspTree.leafCount() == 0 || (oldDepth != depth && qAbs(lastItemCount - indexedItems.size()) > slack)) {
// ### Crude algorithm.
regenerateIndex = true;
}
}
// Regenerate the tree.
if (regenerateIndex) {
regenerateIndex = false;
bspTree.initialize(q->sceneRect(), depth);
unindexedItems = indexedItems;
lastItemCount = indexedItems.size();
q->update();
// Take this opportunity to reset our largest-item counter for
// untransformable items. When the items are inserted into the BSP
// tree, we'll get an accurate calculation.
largestUntransformableItem = QRectF();
}
}
// Insert all unindexed items into the tree.
for (int i = 0; i < unindexedItems.size(); ++i) {
if (QGraphicsItem *item = unindexedItems.at(i)) {
QRectF rect = item->sceneBoundingRect();
if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
continue;
if (indexMethod == QGraphicsScene::BspTreeIndex)
bspTree.insertItem(item, rect);
// If the item ignores view transformations, update our
// largest-item-counter to ensure that the view can accurately
// discover untransformable items when drawing.
if (item->d_ptr->itemIsUntransformable()) {
QGraphicsItem *topmostUntransformable = item;
while (topmostUntransformable && (topmostUntransformable->d_ptr->ancestorFlags
& QGraphicsItemPrivate::AncestorIgnoresTransformations)) {
topmostUntransformable = topmostUntransformable->parentItem();
}
// ### Verify that this is the correct largest untransformable rectangle.
largestUntransformableItem |= item->mapToItem(topmostUntransformable, item->boundingRect()).boundingRect();
}
}
}
unindexedItems.clear();
// Notify scene rect changes.
if (!hasSceneRect && growingItemsBoundingRect != oldGrowingItemsBoundingRect)
emit q->sceneRectChanged(growingItemsBoundingRect);
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_emitUpdated()
{
Q_Q(QGraphicsScene);
calledEmitUpdated = false;
// Ensure all views are connected if anything is connected. This disables
// the optimization that items send updates directly to the views, but it
// needs to happen in order to keep compatibility with the behavior from
// Qt 4.4 and backward.
if (!views.isEmpty() && (connectedSignals & changedSignalMask)) {
for (int i = 0; i < views.size(); ++i) {
QGraphicsView *view = views.at(i);
if (!view->d_func()->connectedToScene) {
view->d_func()->connectedToScene = true;
q->connect(q, SIGNAL(changed(QList<QRectF>)),
views.at(i), SLOT(updateScene(QList<QRectF>)));
}
}
}
// Ensure all dirty items's current positions are recorded in the list of
// updated rects.
for (int i = 0; i < dirtyItems.size(); ++i)
updatedRects += dirtyItems.at(i)->sceneBoundingRect();
// Notify the changes to anybody interested.
QList<QRectF> oldUpdatedRects;
oldUpdatedRects = updateAll ? (QList<QRectF>() << q->sceneRect()) : updatedRects;
updateAll = false;
updatedRects.clear();
emit q->changed(oldUpdatedRects);
}
/*!
\internal
Updates all items in the pending update list. At this point, the list is
unlikely to contain partially constructed items.
*/
void QGraphicsScenePrivate::_q_updateLater()
{
foreach (QGraphicsItem *item, pendingUpdateItems)
item->update();
pendingUpdateItems.clear();
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_polishItems()
{
const QVariant booleanTrueVariant(true);
foreach (QGraphicsItem *item, unpolishedItems) {
if (!item->d_ptr->explicitlyHidden) {
item->itemChange(QGraphicsItem::ItemVisibleChange, booleanTrueVariant);
item->itemChange(QGraphicsItem::ItemVisibleHasChanged, booleanTrueVariant);
}
if (item->isWidget()) {
QEvent event(QEvent::Polish);
QApplication::sendEvent((QGraphicsWidget *)item, &event);
}
}
unpolishedItems.clear();
}
/*!
\internal
*/
void QGraphicsScenePrivate::_q_resetDirtyItems()
{
for (int i = 0; i < dirtyItems.size(); ++i) {
QGraphicsItem *item = dirtyItems.at(i);
item->d_ptr->dirty = 0;
item->d_ptr->dirtyChildren = 0;
}
dirtyItems.clear();
dirtyItemResetPending = false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::resetDirtyItemsLater()
{
Q_Q(QGraphicsScene);
if (dirtyItemResetPending)
return;
// dirtyItems.reserve(indexedItems.size() + unindexedItems.size());
dirtyItemResetPending = true;
QMetaObject::invokeMethod(q, "_q_resetDirtyItems", Qt::QueuedConnection);
}
/*!
\internal
Schedules an item for removal. This function leaves some stale indexes
around in the BSP tree; these will be cleaned up the next time someone
triggers purgeRemovedItems().
Note: This function is called from QGraphicsItem's destructor. \a item is
being destroyed, so we cannot call any pure virtual functions on it (such
as boundingRect()). Also, it is unnecessary to update the item's own state
in any way.
### Refactoring: This function shares much functionality with removeItem()
*/
void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item)
{
Q_Q(QGraphicsScene);
// Clear focus on the item to remove any reference in the focusWidget
// chain.
item->clearFocus();
int index = item->d_func()->index;
if (index != -1) {
// Important: The index is useless until purgeRemovedItems() is
// called.
indexedItems[index] = (QGraphicsItem *)0;
if (!purgePending) {
purgePending = true;
q->update();
}
removedItems << item;
} else {
// Recently added items are purged immediately. unindexedItems() never
// contains stale items.
unindexedItems.removeAll(item);
q->update();
}
// Reset the mouse grabber and focus item data.
if (item == focusItem)
focusItem = 0;
if (item == lastFocusItem)
lastFocusItem = 0;
if (item == activeWindow) {
// ### deactivate...
activeWindow = 0;
}
// Disable selectionChanged() for individual items
++selectionChanging;
int oldSelectedItemsSize = selectedItems.size();
// Update selected & hovered item bookkeeping
selectedItems.remove(item);
hoverItems.removeAll(item);
pendingUpdateItems.removeAll(item);
cachedItemsUnderMouse.removeAll(item);
unpolishedItems.removeAll(item);
dirtyItems.removeAll(item);
//We remove all references of item from the sceneEventFilter arrays
QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = sceneEventFilters.begin();
while (iterator != sceneEventFilters.end()) {
if (iterator.value() == item || iterator.key() == item)
iterator = sceneEventFilters.erase(iterator);
else
++iterator;
}
// Remove from scene transform cache
int transformIndex = item->d_func()->sceneTransformIndex;
if (transformIndex != -1) {
validTransforms.setBit(transformIndex, 0);
freeSceneTransformSlots.append(transformIndex);
}
// Remove all children recursively.
foreach (QGraphicsItem *child, item->children())
_q_removeItemLater(child);
// Reset the mouse grabber
if (mouseGrabberItems.contains(item))
ungrabMouse(item, /* item is dying */ true);
// Reset the keyboard grabber
if (keyboardGrabberItems.contains(item))
ungrabKeyboard(item, /* item is dying */ true);
// Reset the last mouse grabber item
if (item == lastMouseGrabberItem)
lastMouseGrabberItem = 0;
// Reenable selectionChanged() for individual items
--selectionChanging;
if (!selectionChanging && selectedItems.size() != oldSelectedItemsSize)
emit q->selectionChanged();
}
/*!
\internal
Removes stale pointers from all data structures.
*/
void QGraphicsScenePrivate::purgeRemovedItems()
{
Q_Q(QGraphicsScene);
if (!purgePending && removedItems.isEmpty())
return;
// Remove stale items from the BSP tree.
if (indexMethod != QGraphicsScene::NoIndex)
bspTree.removeItems(removedItems);
// Purge this list.
removedItems.clear();
freeItemIndexes.clear();
for (int i = 0; i < indexedItems.size(); ++i) {
if (!indexedItems.at(i))
freeItemIndexes << i;
}
purgePending = false;
// No locality info for the items; update the whole scene.
q->update();
}
/*!
\internal
Starts or restarts the timer used for reindexing unindexed items.
*/
void QGraphicsScenePrivate::startIndexTimer()
{
Q_Q(QGraphicsScene);
if (indexTimerId) {
restartIndexTimer = true;
} else {
indexTimerId = q->startTimer(QGRAPHICSSCENE_INDEXTIMER_TIMEOUT);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::addPopup(QGraphicsWidget *widget)
{
Q_ASSERT(widget);
Q_ASSERT(!popupWidgets.contains(widget));
popupWidgets << widget;
if (QGraphicsWidget *focusWidget = widget->focusWidget()) {
focusWidget->setFocus(Qt::PopupFocusReason);
} else {
grabKeyboard((QGraphicsItem *)widget);
if (focusItem && popupWidgets.size() == 1) {
QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
}
}
grabMouse((QGraphicsItem *)widget);
}
/*!
\internal
Remove \a widget from the popup list. Important notes:
\a widget is guaranteed to be in the list of popups, but it might not be
the last entry; you can hide any item in the pop list before the others,
and this must cause all later mouse grabbers to lose the grab.
*/
void QGraphicsScenePrivate::removePopup(QGraphicsWidget *widget, bool itemIsDying)
{
Q_ASSERT(widget);
int index = popupWidgets.indexOf(widget);
Q_ASSERT(index != -1);
for (int i = popupWidgets.size() - 1; i >= index; --i) {
QGraphicsWidget *widget = popupWidgets.takeLast();
ungrabMouse(widget, itemIsDying);
if (focusItem && popupWidgets.isEmpty()) {
QFocusEvent event(QEvent::FocusIn, Qt::PopupFocusReason);
sendEvent(focusItem, &event);
} else {
ungrabKeyboard((QGraphicsItem *)widget, itemIsDying);
}
if (!itemIsDying && widget->isVisible()) {
widget->hide();
widget->QGraphicsItem::d_ptr->explicitlyHidden = 0;
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabMouse(QGraphicsItem *item, bool implicit)
{
// Append to list of mouse grabber items, and send a mouse grab event.
if (mouseGrabberItems.contains(item)) {
if (mouseGrabberItems.last() == item)
qWarning("QGraphicsItem::grabMouse: already a mouse grabber");
else
qWarning("QGraphicsItem::grabMouse: already blocked by mouse grabber: %p",
mouseGrabberItems.last());
return;
}
// Send ungrab event to the last grabber.
if (!mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
if (lastMouseGrabberItemHasImplicitMouseGrab) {
// Implicit mouse grab is immediately lost.
last->ungrabMouse();
} else {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabMouse);
sendEvent(last, &ungrabEvent);
}
}
mouseGrabberItems << item;
lastMouseGrabberItemHasImplicitMouseGrab = implicit;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabMouse);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabMouse(QGraphicsItem *item, bool itemIsDying)
{
int index = mouseGrabberItems.indexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabMouse: not a mouse grabber");
return;
}
if (item != mouseGrabberItems.last()) {
// Recursively ungrab the next mouse grabber until we reach this item
// to ensure state consistency.
ungrabMouse(mouseGrabberItems.at(index + 1), itemIsDying);
}
if (!popupWidgets.isEmpty() && item == popupWidgets.last()) {
// If the item is a popup, go via removePopup to ensure state
// consistency and that it gets hidden correctly - beware that
// removePopup() reenters this function to continue removing the grab.
removePopup((QGraphicsWidget *)item, itemIsDying);
return;
}
// Send notification about mouse ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabMouse);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers. Whenever this happens, we
// reset the implicitGrab (there can be only ever be one implicit grabber
// in a scene, and it is always the latest grabber; if the implicit grab
// is lost, it is not automatically regained.
mouseGrabberItems.takeLast();
lastMouseGrabberItemHasImplicitMouseGrab = false;
// Send notification about mouse regrab. ### It's unfortunate that all the
// items get a GrabMouse event, but this is a rare case with a simple
// implementation and it does ensure a consistent state.
if (!itemIsDying && !mouseGrabberItems.isEmpty()) {
QGraphicsItem *last = mouseGrabberItems.last();
QEvent event(QEvent::GrabMouse);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearMouseGrabber()
{
if (!mouseGrabberItems.isEmpty())
mouseGrabberItems.first()->ungrabMouse();
lastMouseGrabberItem = 0;
}
/*!
\internal
*/
void QGraphicsScenePrivate::grabKeyboard(QGraphicsItem *item)
{
if (keyboardGrabberItems.contains(item)) {
if (keyboardGrabberItems.last() == item)
qWarning("QGraphicsItem::grabKeyboard: already a keyboard grabber");
else
qWarning("QGraphicsItem::grabKeyboard: already blocked by keyboard grabber: %p",
keyboardGrabberItems.last());
return;
}
// Send ungrab event to the last grabber.
if (!keyboardGrabberItems.isEmpty()) {
// Just send ungrab event to current grabber.
QEvent ungrabEvent(QEvent::UngrabKeyboard);
sendEvent(keyboardGrabberItems.last(), &ungrabEvent);
}
keyboardGrabberItems << item;
// Send grab event to current grabber.
QEvent grabEvent(QEvent::GrabKeyboard);
sendEvent(item, &grabEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::ungrabKeyboard(QGraphicsItem *item, bool itemIsDying)
{
int index = keyboardGrabberItems.lastIndexOf(item);
if (index == -1) {
qWarning("QGraphicsItem::ungrabKeyboard: not a keyboard grabber");
return;
}
if (item != keyboardGrabberItems.last()) {
// Recursively ungrab the topmost keyboard grabber until we reach this
// item to ensure state consistency.
ungrabKeyboard(keyboardGrabberItems.at(index + 1), itemIsDying);
}
// Send notification about keyboard ungrab.
if (!itemIsDying) {
QEvent event(QEvent::UngrabKeyboard);
sendEvent(item, &event);
}
// Remove the item from the list of grabbers.
keyboardGrabberItems.takeLast();
// Send notification about mouse regrab.
if (!itemIsDying && !keyboardGrabberItems.isEmpty()) {
QGraphicsItem *last = keyboardGrabberItems.last();
QEvent event(QEvent::GrabKeyboard);
sendEvent(last, &event);
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::clearKeyboardGrabber()
{
if (!keyboardGrabberItems.isEmpty())
ungrabKeyboard(keyboardGrabberItems.first());
}
/*!
Returns all items for the screen position in \a event.
*/
QList<QGraphicsItem *> QGraphicsScenePrivate::itemsAtPosition(const QPoint &screenPos,
const QPointF &scenePos,
QWidget *widget) const
{
Q_Q(const QGraphicsScene);
QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
QList<QGraphicsItem *> items;
if (view)
items = view->items(view->viewport()->mapFromGlobal(screenPos));
else
items = q->items(scenePos);
return items;
}
/*!
\internal
Checks if item collides with the path and mode, but also checks that if it
doesn't collide, maybe its frame rect will.
*/
bool QGraphicsScenePrivate::itemCollidesWithPath(QGraphicsItem *item,
const QPainterPath &path,
Qt::ItemSelectionMode mode)
{
if (item->collidesWithPath(path, mode))
return true;
if (item->isWidget()) {
// Check if this is a window, and if its frame rect collides.
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (widget->isWindow()) {
QRectF frameRect = widget->windowFrameRect();
QPainterPath framePath;
framePath.addRect(frameRect);
bool intersects = path.intersects(frameRect);
if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect)
return intersects || path.contains(frameRect.topLeft())
|| framePath.contains(path.elementAt(0));
return !intersects && path.contains(frameRect.topLeft());
}
}
return false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::storeMouseButtonsForMouseGrabber(QGraphicsSceneMouseEvent *event)
{
for (int i = 0x1; i <= 0x10; i <<= 1) {
if (event->buttons() & i) {
mouseGrabberButtonDownPos.insert(Qt::MouseButton(i),
mouseGrabberItems.last()->d_ptr->genericMapFromScene(event->scenePos(),
event->widget()));
mouseGrabberButtonDownScenePos.insert(Qt::MouseButton(i), event->scenePos());
mouseGrabberButtonDownScreenPos.insert(Qt::MouseButton(i), event->screenPos());
}
}
}
/*!
\internal
*/
void QGraphicsScenePrivate::installSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
sceneEventFilters.insert(watched, filter);
}
/*!
\internal
*/
void QGraphicsScenePrivate::removeSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
{
if (!sceneEventFilters.contains(watched))
return;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(watched);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(watched);
do {
if (it.value() == filter)
it = sceneEventFilters.erase(it);
else
++it;
} while (it != end);
}
/*!
\internal
*/
bool QGraphicsScenePrivate::filterEvent(QGraphicsItem *item, QEvent *event)
{
if (item && !sceneEventFilters.contains(item))
return false;
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(item);
QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(item);
while (it != end) {
// ### The filterer and filteree might both be deleted.
if (it.value()->sceneEventFilter(it.key(), event))
return true;
++it;
}
return false;
}
/*!
\internal
This is the final dispatch point for any events from the scene to the
item. It filters the event first - if the filter returns true, the event
is considered to have been eaten by the filter, and is therefore stopped
(the default filter returns false). Then/otherwise, if the item is
enabled, the event is sent; otherwise it is stopped.
*/
bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event)
{
if (filterEvent(item, event))
return false;
return (item && item->isEnabled()) ? item->sceneEvent(event) : false;
}
/*!
\internal
*/
void QGraphicsScenePrivate::cloneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
QGraphicsSceneDragDropEvent *source)
{
dest->setWidget(source->widget());
dest->setPos(source->pos());
dest->setScenePos(source->scenePos());
dest->setScreenPos(source->screenPos());
dest->setButtons(source->buttons());
dest->setModifiers(source->modifiers());
dest->setPossibleActions(source->possibleActions());
dest->setProposedAction(source->proposedAction());
dest->setDropAction(source->dropAction());
dest->setSource(source->source());
dest->setMimeData(source->mimeData());
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendDragDropEvent(QGraphicsItem *item,
QGraphicsSceneDragDropEvent *dragDropEvent)
{
dragDropEvent->setPos(item->d_ptr->genericMapFromScene(dragDropEvent->scenePos(), dragDropEvent->widget()));
sendEvent(item, dragDropEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendHoverEvent(QEvent::Type type, QGraphicsItem *item,
QGraphicsSceneHoverEvent *hoverEvent)
{
QGraphicsSceneHoverEvent event(type);
event.setWidget(hoverEvent->widget());
event.setPos(item->d_ptr->genericMapFromScene(hoverEvent->scenePos(), hoverEvent->widget()));
event.setScenePos(hoverEvent->scenePos());
event.setScreenPos(hoverEvent->screenPos());
event.setLastPos(item->d_ptr->genericMapFromScene(hoverEvent->lastScenePos(), hoverEvent->widget()));
event.setLastScenePos(hoverEvent->lastScenePos());
event.setLastScreenPos(hoverEvent->lastScreenPos());
event.setModifiers(hoverEvent->modifiers());
sendEvent(item, &event);
}
/*!
\internal
*/
void QGraphicsScenePrivate::sendMouseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
if (mouseEvent->button() == 0 && mouseEvent->buttons() == 0 && lastMouseGrabberItemHasImplicitMouseGrab) {
// ### This is a temporary fix for until we get proper mouse
// grab events.
clearMouseGrabber();
return;
}
QGraphicsItem *item = mouseGrabberItems.last();
for (int i = 0x1; i <= 0x10; i <<= 1) {
Qt::MouseButton button = Qt::MouseButton(i);
mouseEvent->setButtonDownPos(button, mouseGrabberButtonDownPos.value(button, item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget())));
mouseEvent->setButtonDownScenePos(button, mouseGrabberButtonDownScenePos.value(button, mouseEvent->scenePos()));
mouseEvent->setButtonDownScreenPos(button, mouseGrabberButtonDownScreenPos.value(button, mouseEvent->screenPos()));
}
mouseEvent->setPos(item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget()));
mouseEvent->setLastPos(item->d_ptr->genericMapFromScene(mouseEvent->lastScenePos(), mouseEvent->widget()));
sendEvent(item, mouseEvent);
}
/*!
\internal
*/
void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_Q(QGraphicsScene);
// Ignore by default, unless we find a mouse grabber that accepts it.
mouseEvent->ignore();
// Deliver to any existing mouse grabber.
if (!mouseGrabberItems.isEmpty()) {
// The event is ignored by default, but we disregard the event's
// accepted state after delivery; the mouse is grabbed, after all.
sendMouseEvent(mouseEvent);
return;
}
// Start by determining the number of items at the current position.
// Reuse value from earlier calculations if possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(mouseEvent->screenPos(),
mouseEvent->scenePos(),
mouseEvent->widget());
}
// Update window activation.
QGraphicsWidget *newActiveWindow = windowForItem(cachedItemsUnderMouse.value(0));
if (newActiveWindow != activeWindow)
q->setActiveWindow(newActiveWindow);
// Set focus on the topmost enabled item that can take focus.
bool setFocus = false;
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
setFocus = true;
if (item != q->focusItem())
q->setFocusItem(item, Qt::MouseFocusReason);
break;
}
}
}
// If nobody could take focus, clear it.
if (!stickyFocus && !setFocus)
q->setFocusItem(0, Qt::MouseFocusReason);
// Find a mouse grabber by sending mouse press events to all mouse grabber
// candidates one at a time, until the event is accepted. It's accepted by
// default, so the receiver has to explicitly ignore it for it to pass
// through.
foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
if (!(item->acceptedMouseButtons() & mouseEvent->button())) {
// Skip items that don't accept the event's mouse button.
continue;
}
grabMouse(item, /* implicit = */ true);
mouseEvent->accept();
// check if the item we are sending to are disabled (before we send the event)
bool disabled = !item->isEnabled();
bool isWindow = item->isWindow();
if (mouseEvent->type() == QEvent::GraphicsSceneMouseDoubleClick && item != lastMouseGrabberItem) {
// If this item is different from the item that received the last
// mouse event, and mouseEvent is a doubleclick event, then the
// event is converted to a press. Known limitation:
// Triple-clicking will not generate a doubleclick, though.
QGraphicsSceneMouseEvent mousePress(QEvent::GraphicsSceneMousePress);
mousePress.accept();
mousePress.setButton(mouseEvent->button());
mousePress.setButtons(mouseEvent->buttons());
mousePress.setScreenPos(mouseEvent->screenPos());
mousePress.setScenePos(mouseEvent->scenePos());
mousePress.setModifiers(mouseEvent->modifiers());
mousePress.setWidget(mouseEvent->widget());
mousePress.setButtonDownPos(mouseEvent->button(),
mouseEvent->buttonDownPos(mouseEvent->button()));
mousePress.setButtonDownScenePos(mouseEvent->button(),
mouseEvent->buttonDownScenePos(mouseEvent->button()));
mousePress.setButtonDownScreenPos(mouseEvent->button(),
mouseEvent->buttonDownScreenPos(mouseEvent->button()));
sendMouseEvent(&mousePress);
mouseEvent->setAccepted(mousePress.isAccepted());
} else {
sendMouseEvent(mouseEvent);
}
bool dontSendUngrabEvents = mouseGrabberItems.isEmpty() || mouseGrabberItems.last() != item;
if (disabled) {
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
break;
}
if (mouseEvent->isAccepted()) {
if (!mouseGrabberItems.isEmpty())
storeMouseButtonsForMouseGrabber(mouseEvent);
lastMouseGrabberItem = item;
return;
}
ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
// Don't propagate through windows.
if (isWindow)
break;
}
// Is the event still ignored? Then the mouse press goes to the scene.
// Reset the mouse grabber, clear the selection, clear focus, and leave
// the event ignored so that it can propagate through the originating
// view.
if (!mouseEvent->isAccepted()) {
clearMouseGrabber();
QGraphicsView *view = mouseEvent->widget() ? qobject_cast<QGraphicsView *>(mouseEvent->widget()->parentWidget()) : 0;
bool dontClearSelection = view && view->dragMode() == QGraphicsView::ScrollHandDrag;
if (!dontClearSelection) {
// Clear the selection if the originating view isn't in scroll
// hand drag mode. The view will clear the selection if no drag
// happened.
q->clearSelection();
}
}
}
QGraphicsWidget *QGraphicsScenePrivate::windowForItem(const QGraphicsItem *item) const
{
if (!item)
return 0;
do {
if (item->isWidget())
return static_cast<const QGraphicsWidget *>(item)->window();
item = item->parentItem();
} while (item);
return 0;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPointF &pos) const
{
QList<QGraphicsItem *> items;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
QRectF adjustedRect = QRectF(pos, QSize(1,1));
foreach (QGraphicsItem *item, estimateItemsInRect(adjustedRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
// Rect intersects/contains item's shape
if (QRectF_intersects(adjustedRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (item->contains(xinv.map(pos))) {
items << item;
keep = true;
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(pos));
}
}
sortItems(&items, Qt::AscendingOrder, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QRectF &rect,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
QRectF adjustedRect(rect);
_q_adjustRect(&adjustedRect);
foreach (QGraphicsItem *item, estimateItemsInRect(adjustedRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
QRectF mbr = x.mapRect(br);
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(mbr))) {
items << item;
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(adjustedRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path.isEmpty())
path.addRect(rect);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (x.type() <= QTransform::TxScale) {
// Rect
childItems_helper(&items, item, xinv.mapRect(rect), mode);
} else {
// Polygon
childItems_helper(&items, item, xinv.map(rect), mode);
}
}
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPolygonF &polygon,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QRectF polyRect(polygon.boundingRect());
_q_adjustRect(&polyRect);
QPainterPath path;
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(polyRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(x.mapRect(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(x.mapRect(br)))) {
items << item;
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
// Recurse into children that clip children.
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(polygon), mode);
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPainterPath &path,
Qt::ItemSelectionMode mode,
Qt::SortOrder order) const
{
QList<QGraphicsItem *> items;
QRectF pathRect(path.controlPointRect());
_q_adjustRect(&pathRect);
// The index returns a rough estimate of what items are inside the rect.
// Refine it by iterating through all returned items.
foreach (QGraphicsItem *item, estimateItemsInRect(pathRect)) {
// Find the item's scene transform in a clever way.
QTransform x = item->sceneTransform();
bool keep = false;
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Path contains/intersects item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(x.mapRect(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(x.mapRect(br)))) {
items << item;
keep = true;
}
} else {
// Path contains/intersects item's shape
if (QRectF_intersects(pathRect, x.mapRect(br))) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok) {
if (itemCollidesWithPath(item, xinv.map(path), mode)) {
items << item;
keep = true;
}
}
}
}
if (keep && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) {
bool ok;
QTransform xinv = x.inverted(&ok);
if (ok)
childItems_helper(&items, item, xinv.map(path), mode);
}
}
if (order != Qt::SortOrder(-1))
sortItems(&items, order, sortCacheEnabled);
return items;
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPointF &pos) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
// ### is this needed?
if (parentClip && !parent->boundingRect().contains(pos))
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->hasTransform && !item->transform().isInvertible())
continue;
// Skip invisible items and all their children.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
if (item->contains(item->mapFromParent(pos))) {
items->append(item);
keep = true;
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty())
// Recurse into children.
childItems_helper(items, item, item->mapFromParent(pos));
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QRectF &rect,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
QRectF adjustedRect(rect);
_q_adjustRect(&adjustedRect);
QRectF r = !parentClip ? adjustedRect : adjustedRect.intersected(adjustedItemBoundingRect(parent));
if (r.isEmpty())
return;
QPainterPath path;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->hasTransform && !item->transform().isInvertible())
continue;
// Skip invisible items and all their children.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
QRectF mbr = item->mapRectToParent(br);
if (mode >= Qt::ContainsItemBoundingRect) {
// Rect intersects/contains item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && QRectF_intersects(rect, mbr))
|| (mode == Qt::ContainsItemBoundingRect && rect != mbr && rect.contains(br))) {
items->append(item);
keep = true;
}
} else {
// Rect intersects/contains item's shape
if (QRectF_intersects(rect, mbr)) {
if (path == QPainterPath())
path.addRect(rect);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children.
if (!item->d_ptr->hasTransform || item->transform().type() <= QTransform::TxScale) {
// Rect
childItems_helper(items, item, item->mapRectFromParent(rect), mode);
} else {
// Polygon
childItems_helper(items, item, item->mapFromParent(rect), mode);
}
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPolygonF &polygon,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
QRectF polyRect(polygon.boundingRect());
_q_adjustRect(&polyRect);
QRectF r = !parentClip ? polyRect : polyRect.intersected(adjustedItemBoundingRect(parent));
if (r.isEmpty())
return;
QPainterPath path;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->hasTransform && !item->transform().isInvertible())
continue;
// Skip invisible items.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if (path == QPainterPath())
path.addPolygon(polygon);
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(item->mapRectToParent(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(item->mapRectToParent(br)))) {
items->append(item);
keep = true;
}
} else {
// Polygon contains/intersects item's shape
if (QRectF_intersects(polyRect, item->mapRectToParent(br))) {
if (path == QPainterPath())
path.addPolygon(polygon);
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children that clip children.
childItems_helper(items, item, item->mapFromParent(polygon), mode);
}
}
}
void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items,
const QGraphicsItem *parent,
const QPainterPath &path,
Qt::ItemSelectionMode mode) const
{
bool parentClip = (parent->flags() & QGraphicsItem::ItemClipsChildrenToShape);
if (parentClip && parent->d_ptr->isClippedAway())
return;
QRectF pathRect(path.boundingRect());
_q_adjustRect(&pathRect);
QRectF r = !parentClip ? pathRect : pathRect.intersected(adjustedItemBoundingRect(parent));
if (r.isEmpty())
return;
QList<QGraphicsItem *> &children = parent->d_ptr->children;
for (int i = 0; i < children.size(); ++i) {
QGraphicsItem *item = children.at(i);
if (item->d_ptr->hasTransform && !item->transform().isInvertible())
continue;
// Skip invisible items.
if (item->d_ptr->isInvisible())
continue;
bool keep = false;
if (!item->d_ptr->isClippedAway()) {
// ### _q_adjustedRect is only needed because QRectF::intersects,
// QRectF::contains and QTransform::map() and friends don't work with
// flat rectangles.
const QRectF br(adjustedItemBoundingRect(item));
if (mode >= Qt::ContainsItemBoundingRect) {
// Polygon contains/intersects item's bounding rect
if ((mode == Qt::IntersectsItemBoundingRect && path.intersects(item->mapRectToParent(br)))
|| (mode == Qt::ContainsItemBoundingRect && path.contains(item->mapRectToParent(br)))) {
items->append(item);
keep = true;
}
} else {
// Path contains/intersects item's shape
if (QRectF_intersects(pathRect, item->mapRectToParent(br))) {
if (itemCollidesWithPath(item, item->mapFromParent(path), mode)) {
items->append(item);
keep = true;
}
}
}
}
if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) {
// Recurse into children that clip children.
childItems_helper(items, item, item->mapFromParent(path), mode);
}
}
}
void QGraphicsScenePrivate::invalidateSortCache()
{
Q_Q(QGraphicsScene);
if (!sortCacheEnabled || updatingSortCache)
return;
updatingSortCache = true;
QMetaObject::invokeMethod(q, "_q_updateSortCache", Qt::QueuedConnection);
}
/*!
\internal
Should not be exported, but we can't change that now.
### Qt 5: Remove symbol / make static
*/
inline bool qt_closestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Return true if sibling item1 is on top of item2.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
bool f1 = d1->flags & QGraphicsItem::ItemStacksBehindParent;
bool f2 = d2->flags & QGraphicsItem::ItemStacksBehindParent;
if (f1 != f2) return f2;
qreal z1 = d1->z;
qreal z2 = d2->z;
return z1 != z2 ? z1 > z2 : item1 > item2;
}
/*!
\internal
Should not be exported, but we can't change that now.
*/
inline bool qt_closestItemFirst(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return QGraphicsScenePrivate::closestItemFirst_withoutCache(item1, item2);
}
/*!
Returns true if \a item1 is on top of \a item2.
\internal
*/
bool QGraphicsScenePrivate::closestItemFirst_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
// Siblings? Just check their z-values.
const QGraphicsItemPrivate *d1 = item1->d_ptr;
const QGraphicsItemPrivate *d2 = item2->d_ptr;
if (d1->parent == d2->parent)
return qt_closestLeaf(item1, item2);
// Find common ancestor, and each item's ancestor closest to the common
// ancestor.
int item1Depth = d1->depth;
int item2Depth = d2->depth;
const QGraphicsItem *p = item1;
const QGraphicsItem *t1 = item1;
while (item1Depth > item2Depth && (p = p->d_ptr->parent)) {
if (p == item2) {
// item2 is one of item1's ancestors; item1 is on top
return !(t1->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t1 = p;
--item1Depth;
}
p = item2;
const QGraphicsItem *t2 = item2;
while (item2Depth > item1Depth && (p = p->d_ptr->parent)) {
if (p == item1) {
// item1 is one of item2's ancestors; item1 is not on top
return (t2->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
}
t2 = p;
--item2Depth;
}
// item1Ancestor is now at the same level as item2Ancestor, but not the same.
const QGraphicsItem *a1 = t1;
const QGraphicsItem *a2 = t2;
while (a1) {
const QGraphicsItem *p1 = a1;
const QGraphicsItem *p2 = a2;
a1 = a1->parentItem();
a2 = a2->parentItem();
if (a1 && a1 == a2)
return qt_closestLeaf(p1, p2);
}
// No common ancestor? Then just compare the items' toplevels directly.
return qt_closestLeaf(t1->topLevelItem(), t2->topLevelItem());
}
/*!
Returns true if \a item2 is on top of \a item1.
\internal
*/
bool QGraphicsScenePrivate::closestItemLast_withoutCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
{
return closestItemFirst_withoutCache(item2, item1);
}
void QGraphicsScenePrivate::climbTree(QGraphicsItem *item, int *stackingOrder)
{
if (!item->d_ptr->children.isEmpty()) {
QList<QGraphicsItem *> childList = item->d_ptr->children;
qSort(childList.begin(), childList.end(), qt_closestLeaf);
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (!(item->flags() & QGraphicsItem::ItemStacksBehindParent))
climbTree(childList.at(i), stackingOrder);
}
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
for (int i = 0; i < childList.size(); ++i) {
QGraphicsItem *item = childList.at(i);
if (item->flags() & QGraphicsItem::ItemStacksBehindParent)
climbTree(childList.at(i), stackingOrder);
}
} else {
item->d_ptr->globalStackingOrder = (*stackingOrder)++;
}
}
void QGraphicsScenePrivate::_q_updateSortCache()
{
_q_updateIndex();
if (!sortCacheEnabled || !updatingSortCache)
return;
updatingSortCache = false;
int stackingOrder = 0;
QList<QGraphicsItem *> topLevels;
for (int i = 0; i < indexedItems.size(); ++i) {
QGraphicsItem *item = indexedItems.at(i);
if (item && item->parentItem() == 0)
topLevels << item;
}
for (int i = 0; i < unindexedItems.size(); ++i) {
QGraphicsItem *item = unindexedItems.at(i);
if (item->parentItem() == 0)
topLevels << item;
}
qSort(topLevels.begin(), topLevels.end(), qt_closestLeaf);
for (int i = 0; i < topLevels.size(); ++i)
climbTree(topLevels.at(i), &stackingOrder);
}
void QGraphicsScenePrivate::sortItems(QList<QGraphicsItem *> *itemList, Qt::SortOrder order,
bool sortCacheEnabled)
{
if (sortCacheEnabled) {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withCache);
}
} else {
if (order == Qt::AscendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemFirst_withoutCache);
} else if (order == Qt::DescendingOrder) {
qSort(itemList->begin(), itemList->end(), closestItemLast_withoutCache);
}
}
}
/*!
\internal
Set the font and propagate the changes if the font is different from the
current font.
*/
void QGraphicsScenePrivate::setFont_helper(const QFont &font)
{
if (this->font == font && this->font.resolve() == font.resolve())
return;
updateFont(font);
}
/*!
\internal
Resolve the scene's font against the application font, and propagate the
changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolveFont()
{
QFont naturalFont = qApp->font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
updateFont(resolvedFont);
}
/*!
\internal
Update the font, and whether or not it has changed, reresolve all fonts in
the scene.
*/
void QGraphicsScenePrivate::updateFont(const QFont &font)
{
Q_Q(QGraphicsScene);
// Update local font setting.
this->font = font;
// Resolve the fonts of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolveFont(font.resolve());
}
}
// Send the scene a FontChange event.
QEvent event(QEvent::FontChange);
QApplication::sendEvent(q, &event);
}
/*!
\internal
Set the palette and propagate the changes if the palette is different from
the current palette.
*/
void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
{
if (this->palette == palette && this->palette.resolve() == palette.resolve())
return;
updatePalette(palette);
}
/*!
\internal
Resolve the scene's palette against the application palette, and propagate
the changes too all items in the scene.
*/
void QGraphicsScenePrivate::resolvePalette()
{
QPalette naturalPalette = qApp->palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
updatePalette(resolvedPalette);
}
/*!
\internal
Update the palette, and whether or not it has changed, reresolve all
palettes in the scene.
*/
void QGraphicsScenePrivate::updatePalette(const QPalette &palette)
{
Q_Q(QGraphicsScene);
// Update local palette setting.
this->palette = palette;
// Resolve the palettes of all top-level widget items, or widget items
// whose parent is not a widget.
foreach (QGraphicsItem *item, q->items()) {
if (!item->parentItem()) {
// Resolvefont for an item is a noop operation, but
// every item can be a widget, or can have a widget
// childre.
item->d_ptr->resolvePalette(palette.resolve());
}
}
// Send the scene a PaletteChange event.
QEvent event(QEvent::PaletteChange);
QApplication::sendEvent(q, &event);
}
/*!
Constructs a QGraphicsScene object. The \a parent parameter is
passed to QObject's constructor.
*/
QGraphicsScene::QGraphicsScene(QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using \a sceneRect for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(const QRectF &sceneRect, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(sceneRect);
d_func()->init();
}
/*!
Constructs a QGraphicsScene object, using the rectangle specified
by (\a x, \a y), and the given \a width and \a height for its
scene rectangle. The \a parent parameter is passed to QObject's
constructor.
\sa sceneRect
*/
QGraphicsScene::QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent)
: QObject(*new QGraphicsScenePrivate, parent)
{
setSceneRect(x, y, width, height);
d_func()->init();
}
/*!
Destroys the QGraphicsScene object.
*/
QGraphicsScene::~QGraphicsScene()
{
Q_D(QGraphicsScene);
// Remove this scene from qApp's global scene list.
qApp->d_func()->scene_list.removeAll(this);
clear();
// Remove this scene from all associated views.
for (int j = 0; j < d->views.size(); ++j)
d->views.at(j)->setScene(0);
}
/*!
\property QGraphicsScene::sceneRect
\brief the scene rectangle; the bounding rectangle of the scene
The scene rectangle defines the extent of the scene. It is
primarily used by QGraphicsView to determine the view's default
scrollable area, and by QGraphicsScene to manage item indexing.
If unset, or if set to a null QRectF, sceneRect() will return the largest
bounding rect of all items on the scene since the scene was created (i.e.,
a rectangle that grows when items are added to or moved in the scene, but
never shrinks).
\sa width(), height(), QGraphicsView::sceneRect
*/
QRectF QGraphicsScene::sceneRect() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->_q_updateIndex();
return d->hasSceneRect ? d->sceneRect : d->growingItemsBoundingRect;
}
void QGraphicsScene::setSceneRect(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (rect != d->sceneRect) {
d->hasSceneRect = !rect.isNull();
d->sceneRect = rect;
d->resetIndex();
emit sceneRectChanged(rect);
}
}
/*!
\fn qreal QGraphicsScene::width() const
This convenience function is equivalent to calling sceneRect().width().
\sa height()
*/
/*!
\fn qreal QGraphicsScene::height() const
This convenience function is equivalent to calling \c sceneRect().height().
\sa width()
*/
/*!
Renders the \a source rect from scene into \a target, using \a painter. This
function is useful for capturing the contents of the scene onto a paint
device, such as a QImage (e.g., to take a screenshot), or for printing
with QPrinter. For example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 1
If \a source is a null rect, this function will use sceneRect() to
determine what to render. If \a target is a null rect, the dimensions of \a
painter's paint device will be used.
The source rect contents will be transformed according to \a
aspectRatioMode to fit into the target rect. By default, the aspect ratio
is kept, and \a source is scaled to fit in \a target.
\sa QGraphicsView::render()
*/
void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRectF &source,
Qt::AspectRatioMode aspectRatioMode)
{
Q_D(QGraphicsScene);
// Default source rect = scene rect
QRectF sourceRect = source;
if (sourceRect.isNull())
sourceRect = sceneRect();
// Default target rect = device rect
QRectF targetRect = target;
if (targetRect.isNull()) {
if (painter->device()->devType() == QInternal::Picture)
targetRect = sourceRect;
else
targetRect.setRect(0, 0, painter->device()->width(), painter->device()->height());
}
// Find the ideal x / y scaling ratio to fit \a source into \a target.
qreal xratio = targetRect.width() / sourceRect.width();
qreal yratio = targetRect.height() / sourceRect.height();
// Scale according to the aspect ratio mode.
switch (aspectRatioMode) {
case Qt::KeepAspectRatio:
xratio = yratio = qMin(xratio, yratio);
break;
case Qt::KeepAspectRatioByExpanding:
xratio = yratio = qMax(xratio, yratio);
break;
case Qt::IgnoreAspectRatio:
break;
}
// Find all items to draw, and reverse the list (we want to draw
// in reverse order).
QList<QGraphicsItem *> itemList = items(sourceRect, Qt::IntersectsItemBoundingRect);
QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
int numItems = itemList.size();
for (int i = 0; i < numItems; ++i)
itemArray[numItems - i - 1] = itemList.at(i);
itemList.clear();
painter->save();
// Transform the painter.
painter->setClipRect(targetRect);
QTransform painterTransform;
painterTransform *= QTransform()
.translate(targetRect.left(), targetRect.top())
.scale(xratio, yratio)
.translate(-sourceRect.left(), -sourceRect.top());
painter->setWorldTransform(painterTransform, true);
// Two unit vectors.
QLineF v1(0, 0, 1, 0);
QLineF v2(0, 0, 0, 1);
// Generate the style options
QStyleOptionGraphicsItem *styleOptionArray = new QStyleOptionGraphicsItem[numItems];
for (int i = 0; i < numItems; ++i) {
QGraphicsItem *item = itemArray[i];
QStyleOptionGraphicsItem option;
option.state = QStyle::State_None;
option.rect = item->boundingRect().toRect();
if (item->isSelected())
option.state |= QStyle::State_Selected;
if (item->isEnabled())
option.state |= QStyle::State_Enabled;
if (item->hasFocus())
option.state |= QStyle::State_HasFocus;
if (d->hoverItems.contains(item))
option.state |= QStyle::State_MouseOver;
if (item == mouseGrabberItem())
option.state |= QStyle::State_Sunken;
// Calculate a simple level-of-detail metric.
// ### almost identical code in QGraphicsView::paintEvent()
// and QGraphicsView::render() - consider refactoring
QTransform itemToDeviceTransform;
if (item->d_ptr->itemIsUntransformable()) {
itemToDeviceTransform = item->deviceTransform(painterTransform);
} else {
itemToDeviceTransform = item->sceneTransform() * painterTransform;
}
option.levelOfDetail = qSqrt(itemToDeviceTransform.map(v1).length() * itemToDeviceTransform.map(v2).length());
option.matrix = itemToDeviceTransform.toAffine(); //### discards perspective
option.exposedRect = item->boundingRect();
option.exposedRect &= itemToDeviceTransform.inverted().mapRect(targetRect);
styleOptionArray[i] = option;
}
// Render the scene.
drawBackground(painter, sourceRect);
drawItems(painter, numItems, itemArray, styleOptionArray);
drawForeground(painter, sourceRect);
delete [] itemArray;
delete [] styleOptionArray;
painter->restore();
}
/*!
\property QGraphicsScene::itemIndexMethod
\brief the item indexing method.
QGraphicsScene applies an indexing algorithm to the scene, to speed up
item discovery functions like items() and itemAt(). Indexing is most
efficient for static scenes (i.e., where items don't move around). For
dynamic scenes, or scenes with many animated items, the index bookkeeping
can outweight the fast lookup speeds.
For the common case, the default index method BspTreeIndex works fine. If
your scene uses many animations and you are experiencing slowness, you can
disable indexing by calling \c setItemIndexMethod(NoIndex).
\sa bspTreeDepth
*/
QGraphicsScene::ItemIndexMethod QGraphicsScene::itemIndexMethod() const
{
Q_D(const QGraphicsScene);
return d->indexMethod;
}
void QGraphicsScene::setItemIndexMethod(ItemIndexMethod method)
{
Q_D(QGraphicsScene);
d->resetIndex();
d->indexMethod = method;
}
/*!
\property QGraphicsScene::bspTreeDepth
\brief the depth of QGraphicsScene's BSP index tree
\since 4.3
This property has no effect when NoIndex is used.
This value determines the depth of QGraphicsScene's BSP tree. The depth
directly affects QGraphicsScene's performance and memory usage; the latter
growing exponentially with the depth of the tree. With an optimal tree
depth, QGraphicsScene can instantly determine the locality of items, even
for scenes with thousands or millions of items. This also greatly improves
rendering performance.
By default, the value is 0, in which case Qt will guess a reasonable
default depth based on the size, location and number of items in the
scene. If these parameters change frequently, however, you may experience
slowdowns as QGraphicsScene retunes the depth internally. You can avoid
potential slowdowns by fixating the tree depth through setting this
property.
The depth of the tree and the size of the scene rectangle decide the
granularity of the scene's partitioning. The size of each scene segment is
determined by the following algorithm:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 2
The BSP tree has an optimal size when each segment contains between 0 and
10 items.
\sa itemIndexMethod
*/
int QGraphicsScene::bspTreeDepth() const
{
Q_D(const QGraphicsScene);
return d->bspTreeDepth;
}
void QGraphicsScene::setBspTreeDepth(int depth)
{
Q_D(QGraphicsScene);
if (d->bspTreeDepth == depth)
return;
if (depth < 0) {
qWarning("QGraphicsScene::setBspTreeDepth: invalid depth %d ignored; must be >= 0", depth);
return;
}
d->bspTreeDepth = depth;
d->resetIndex();
}
/*!
\property QGraphicsScene::sortCacheEnabled
\brief whether sort caching is enabled
\since 4.5
When enabled, this property adds a cache that speeds up sorting and
transformations for scenes with deep hierarchies (i.e., items with many
levels of descendents), at the cost of using more memory (approx. 100 more
bytes of memory per item).
Items that are not part of a deep hierarchy suffer no penalty from this
cache.
*/
bool QGraphicsScene::isSortCacheEnabled() const
{
Q_D(const QGraphicsScene);
return d->sortCacheEnabled;
}
void QGraphicsScene::setSortCacheEnabled(bool enabled)
{
Q_D(QGraphicsScene);
if (enabled == d->sortCacheEnabled)
return;
if ((d->sortCacheEnabled = enabled))
d->invalidateSortCache();
}
/*!
Calculates and returns the bounding rect of all items on the scene. This
function works by iterating over all items, and because if this, it can
be slow for large scenes.
\sa sceneRect()
*/
QRectF QGraphicsScene::itemsBoundingRect() const
{
QRectF boundingRect;
foreach (QGraphicsItem *item, items())
boundingRect |= item->sceneBoundingRect();
return boundingRect;
}
/*!
Returns a list of all items on the scene, in no particular order.
\sa addItem(), removeItem()
*/
QList<QGraphicsItem *> QGraphicsScene::items() const
{
Q_D(const QGraphicsScene);
const_cast<QGraphicsScenePrivate *>(d)->purgeRemovedItems();
// If freeItemIndexes is empty, we know there are no holes in indexedItems and
// unindexedItems.
if (d->freeItemIndexes.isEmpty()) {
if (d->unindexedItems.isEmpty())
return d->indexedItems;
return d->indexedItems + d->unindexedItems;
}
// Rebuild the list of items to avoid holes. ### We could also just
// compress the item lists at this point.
QList<QGraphicsItem *> itemList;
foreach (QGraphicsItem *item, d->indexedItems + d->unindexedItems) {
if (item)
itemList << item;
}
return itemList;
}
/*!
Returns all visible items at position \a pos in the scene. The items are
listed in descending Z order (i.e., the first item in the list is the
top-most item, and the last item is the bottom-most item).
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos) const
{
Q_D(const QGraphicsScene);
return d->items_helper(pos);
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rectangle, Qt::ItemSelectionMode mode) const
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the specified \a rectangle.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a rectangle are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(rect, mode, Qt::AscendingOrder);
}
/*!
\fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode) const
\since 4.3
This convenience function is equivalent to calling items(QRectF(\a x, \a y, \a w, \a h), \a mode).
*/
/*!
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the polygon \a polygon.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a polygon are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(polygon, mode, Qt::AscendingOrder);
}
/*!
\overload
Returns all visible items that, depending on \a path, are either inside or
intersect with the path \a path.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a path are returned.
\sa itemAt()
*/
QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
return d->items_helper(path, mode, Qt::AscendingOrder);
}
/*!
Returns a list of all items that collide with \a item. Collisions are
determined by calling QGraphicsItem::collidesWithItem(); the collision
detection is determined by \a mode. By default, all items whose shape
intersects \a item or is contained inside \a item's shape are returned.
The items are returned in descending Z order (i.e., the first item in the
list is the top-most item, and the last item is the bottom-most item).
\sa items(), itemAt(), QGraphicsItem::collidesWithItem()
*/
QList<QGraphicsItem *> QGraphicsScene::collidingItems(const QGraphicsItem *item,
Qt::ItemSelectionMode mode) const
{
Q_D(const QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::collidingItems: cannot find collisions for null item");
return QList<QGraphicsItem *>();
}
QList<QGraphicsItem *> tmp;
foreach (QGraphicsItem *itemInVicinity, d->estimateItemsInRect(item->sceneBoundingRect())) {
if (item != itemInVicinity && item->collidesWithItem(itemInVicinity, mode))
tmp << itemInVicinity;
}
d->sortItems(&tmp, Qt::AscendingOrder, d->sortCacheEnabled);
return tmp;
}
/*!
\fn QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position) const
Returns the topmost visible item at the specified \a position, or 0 if
there are no items at this position.
\note The topmost item is the one with the highest Z-value.
\sa items(), collidingItems(), QGraphicsItem::setZValue()
*/
QGraphicsItem *QGraphicsScene::itemAt(const QPointF &pos) const
{
QList<QGraphicsItem *> itemsAtPoint = items(pos);
return itemsAtPoint.isEmpty() ? 0 : itemsAtPoint.first();
}
/*!
\fn QGraphicsScene::itemAt(qreal x, qreal y) const
\overload
Returns the topmost item at the position specified by (\a x, \a
y), or 0 if there are no items at this position.
This convenience function is equivalent to calling \c
{itemAt(QPointF(x, y))}.
\note The topmost item is the one with the highest Z-value.
*/
/*!
Returns a list of all currently selected items. The items are
returned in no particular order.
\sa setSelectionArea()
*/
QList<QGraphicsItem *> QGraphicsScene::selectedItems() const
{
Q_D(const QGraphicsScene);
// Optimization: Lazily removes items that are not selected.
QGraphicsScene *that = const_cast<QGraphicsScene *>(this);
QSet<QGraphicsItem *> actuallySelectedSet;
foreach (QGraphicsItem *item, that->d_func()->selectedItems) {
if (item->isSelected())
actuallySelectedSet << item;
}
that->d_func()->selectedItems = actuallySelectedSet;
return d->selectedItems.values();
}
/*!
Returns the selection area that was previously set with
setSelectionArea(), or an empty QPainterPath if no selection area has been
set.
\sa setSelectionArea()
*/
QPainterPath QGraphicsScene::selectionArea() const
{
Q_D(const QGraphicsScene);
return d->selectionArea;
}
/*!
Sets the selection area to \a path. All items within this area are
immediately selected, and all items outside are unselected. You can get
the list of all selected items by calling selectedItems().
For an item to be selected, it must be marked as \e selectable
(QGraphicsItem::ItemIsSelectable).
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path)
{
setSelectionArea(path, Qt::IntersectsItemShape);
}
/*!
\overload
\since 4.3
Sets the selection area to \a path using \a mode to determine if items are
included in the selection area.
\sa clearSelection(), selectionArea()
*/
void QGraphicsScene::setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode)
{
Q_D(QGraphicsScene);
// Note: with boolean path operations, we can improve performance here
// quite a lot by "growing" the old path instead of replacing it. That
// allows us to only check the intersect area for changes, instead of
// reevaluating the whole path over again.
d->selectionArea = path;
QSet<QGraphicsItem *> unselectItems = d->selectedItems;
// Disable emitting selectionChanged() for individual items.
++d->selectionChanging;
bool changed = false;
// Set all items in path to selected.
foreach (QGraphicsItem *item, items(path, mode)) {
if (item->flags() & QGraphicsItem::ItemIsSelectable) {
if (!item->isSelected())
changed = true;
unselectItems.remove(item);
item->setSelected(true);
}
}
// Unselect all items outside path.
foreach (QGraphicsItem *item, unselectItems) {
item->setSelected(false);
changed = true;
}
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
Clears the current selection.
\sa setSelectionArea(), selectedItems()
*/
void QGraphicsScene::clearSelection()
{
Q_D(QGraphicsScene);
// Disable emitting selectionChanged
++d->selectionChanging;
bool changed = !d->selectedItems.isEmpty();
foreach (QGraphicsItem *item, d->selectedItems)
item->setSelected(false);
d->selectedItems.clear();
// Reenable emitting selectionChanged() for individual items.
--d->selectionChanging;
if (!d->selectionChanging && changed)
emit selectionChanged();
}
/*!
\since 4.4
Removes and deletes all items from the scene, but otherwise leaves the
state of the scene unchanged.
\sa addItem()
*/
void QGraphicsScene::clear()
{
Q_D(QGraphicsScene);
// Recursive descent delete
for (int i = 0; i < d->indexedItems.size(); ++i) {
if (QGraphicsItem *item = d->indexedItems.at(i)) {
if (!item->parentItem())
delete item;
}
}
QList<QGraphicsItem *> unindexedParents;
for (int i = 0; i < d->unindexedItems.size(); ++i) {
QGraphicsItem *item = d->unindexedItems.at(i);
if (!item->parentItem())
unindexedParents << item;
}
d->unindexedItems.clear();
qDeleteAll(unindexedParents);
d->indexedItems.clear();
d->freeItemIndexes.clear();
d->lastItemCount = 0;
d->bspTree.clear();
d->largestUntransformableItem = QRectF();
}
/*!
Groups all items in \a items into a new QGraphicsItemGroup, and returns a
pointer to the group. The group is created with the common ancestor of \a
items as its parent, and with position (0, 0). The items are all
reparented to the group, and their positions and transformations are
mapped to the group. If \a items is empty, this function will return an
empty top-level QGraphicsItemGroup.
QGraphicsScene has ownership of the group item; you do not need to delete
it. To dismantle (ungroup) a group, call destroyItemGroup().
\sa destroyItemGroup(), QGraphicsItemGroup::addToGroup()
*/
QGraphicsItemGroup *QGraphicsScene::createItemGroup(const QList<QGraphicsItem *> &items)
{
// Build a list of the first item's ancestors
QList<QGraphicsItem *> ancestors;
int n = 0;
if (!items.isEmpty()) {
QGraphicsItem *parent = items.at(n++);
while ((parent = parent->parentItem()))
ancestors.append(parent);
}
// Find the common ancestor for all items
QGraphicsItem *commonAncestor = 0;
if (!ancestors.isEmpty()) {
while (n < items.size()) {
int commonIndex = -1;
QGraphicsItem *parent = items.at(n++);
do {
int index = ancestors.indexOf(parent, qMax(0, commonIndex));
if (index != -1) {
commonIndex = index;
break;
}
} while ((parent = parent->parentItem()));
if (commonIndex == -1) {
commonAncestor = 0;
break;
}
commonAncestor = ancestors.at(commonIndex);
}
}
// Create a new group at that level
QGraphicsItemGroup *group = new QGraphicsItemGroup(commonAncestor);
if (!commonAncestor)
addItem(group);
foreach (QGraphicsItem *item, items)
group->addToGroup(item);
return group;
}
/*!
Reparents all items in \a group to \a group's parent item, then removes \a
group from the scene, and finally deletes it. The items' positions and
transformations are mapped from the group to the group's parent.
\sa createItemGroup(), QGraphicsItemGroup::removeFromGroup()
*/
void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup *group)
{
foreach (QGraphicsItem *item, group->children())
group->removeFromGroup(item);
removeItem(group);
delete group;
}
/*!
Adds or moves the item \a item and all its childen to the scene.
If the item is visible (i.e., QGraphicsItem::isVisible() returns
true), QGraphicsScene will emit changed() once control goes back
to the event loop.
If the item is already in a different scene, it will first be removed from
its old scene, and then added to this scene as a top-level.
QGraphicsScene will send ItemSceneChange notifications to \a item while
it is added to the scene. If item does not currently belong to a scene, only one
notification is sent. If it does belong to scene already (i.e., it is
moved to this scene), QGraphicsScene will send an addition notification as
the item is removed from its previous scene.
\sa removeItem(), addEllipse(), addLine(), addPath(), addPixmap(),
addRect(), addText(), addWidget()
*/
void QGraphicsScene::addItem(QGraphicsItem *item)
{
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::addItem: cannot add null item");
return;
}
if (item->scene() == this) {
qWarning("QGraphicsScene::addItem: item has already been added to this scene");
return;
}
// Remove this item from its existing scene
if (QGraphicsScene *oldScene = item->scene())
oldScene->removeItem(item);
// Notify the item that its scene is changing, and allow the item to
// react.
const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(this)));
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(newSceneVariant);
if (targetScene != this) {
if (targetScene && item->scene() != targetScene)
targetScene->addItem(item);
return;
}
// Prevent reusing a recently deleted pointer: purge all removed items
// from our lists.
d->purgeRemovedItems();
// Invalidate any sort caching; arrival of a new item means we need to
// resort.
d->invalidateSortCache();
// Detach this item from its parent if the parent's scene is different
// from this scene.
if (QGraphicsItem *itemParent = item->parentItem()) {
if (itemParent->scene() != this)
item->setParentItem(0);
}
// Add the item to this scene
item->d_func()->scene = targetScene;
// Indexing requires sceneBoundingRect(), but because \a item might
// not be completely constructed at this point, we need to store it in
// a temporary list and schedule an indexing for later.
d->unindexedItems << item;
item->d_func()->index = -1;
d->startIndexTimer();
// Update the scene's sort cache settings.
item->d_ptr->globalStackingOrder = -1;
d->invalidateSortCache();
// Add to list of items that require an update. We cannot assume that the
// item is fully constructed, so calling item->update() can lead to a pure
// virtual function call to boundingRect().
if (!d->updateAll) {
if (d->pendingUpdateItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_updateLater", Qt::QueuedConnection);
d->pendingUpdateItems << item;
}
// Disable selectionChanged() for individual items
++d->selectionChanging;
int oldSelectedItemSize = d->selectedItems.size();
// Update selection lists
if (item->isSelected())
d->selectedItems << item;
if (item->isWidget() && item->isVisible() && static_cast<QGraphicsWidget *>(item)->windowType() == Qt::Popup)
d->addPopup(static_cast<QGraphicsWidget *>(item));
// Update creation order focus chain. Make sure to leave the widget's
// internal tab order intact.
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!d->tabFocusFirst) {
// No first tab focus widget - make this the first tab focus
// widget.
d->tabFocusFirst = widget;
} else if (!widget->parentWidget()) {
// Adding a widget that is not part of a tab focus chain.
QGraphicsWidget *last = d->tabFocusFirst->d_func()->focusPrev;
QGraphicsWidget *lastNew = widget->d_func()->focusPrev;
last->d_func()->focusNext = widget;
widget->d_func()->focusPrev = last;
d->tabFocusFirst->d_func()->focusPrev = lastNew;
lastNew->d_func()->focusNext = d->tabFocusFirst;
}
}
// Add all children recursively
foreach (QGraphicsItem *child, item->children())
addItem(child);
// Resolve font and palette.
item->d_ptr->resolveFont(d->font.resolve());
item->d_ptr->resolvePalette(d->palette.resolve());
if (!item->d_ptr->explicitlyHidden) {
if (d->unpolishedItems.isEmpty())
QMetaObject::invokeMethod(this, "_q_polishItems", Qt::QueuedConnection);
d->unpolishedItems << item;
}
// Reenable selectionChanged() for individual items
--d->selectionChanging;
if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemSize)
emit selectionChanged();
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
}
/*!
Creates and adds an ellipse item to the scene, and returns the item
pointer. The geometry of the ellipse is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addLine(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsEllipseItem *QGraphicsScene::addEllipse(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsEllipseItem *item = new QGraphicsEllipseItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsEllipseItem *QGraphicsScene::addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addEllipse(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a line item to the scene, and returns the item
pointer. The geometry of the line is defined by \a line, and its pen
is initialized to \a pen.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addPath(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsLineItem *QGraphicsScene::addLine(const QLineF &line, const QPen &pen)
{
QGraphicsLineItem *item = new QGraphicsLineItem(line);
item->setPen(pen);
addItem(item);
return item;
}
/*!
\fn QGraphicsLineItem *QGraphicsScene::addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen &pen)
\since 4.3
This convenience function is equivalent to calling addLine(QLineF(\a x1,
\a y1, \a x2, \a y2), \a pen).
*/
/*!
Creates and adds a path item to the scene, and returns the item
pointer. The geometry of the path is defined by \a path, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPathItem *QGraphicsScene::addPath(const QPainterPath &path, const QPen &pen, const QBrush &brush)
{
QGraphicsPathItem *item = new QGraphicsPathItem(path);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a pixmap item to the scene, and returns the item
pointer. The pixmap is defined by \a pixmap.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPixmapItem *QGraphicsScene::addPixmap(const QPixmap &pixmap)
{
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
addItem(item);
return item;
}
/*!
Creates and adds a polygon item to the scene, and returns the item
pointer. The polygon is defined by \a polygon, and its pen and
brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
addWidget()
*/
QGraphicsPolygonItem *QGraphicsScene::addPolygon(const QPolygonF &polygon,
const QPen &pen, const QBrush &brush)
{
QGraphicsPolygonItem *item = new QGraphicsPolygonItem(polygon);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
Creates and adds a rectangle item to the scene, and returns the item
pointer. The geometry of the rectangle is defined by \a rect, and its pen
and brush are initialized to \a pen and \a brush.
Note that the item's geometry is provided in item coordinates, and its
position is initialized to (0, 0). For example, if a QRect(50, 50, 100,
100) is added, its top-left corner will be at (50, 50) relative to the
origin in the items coordinate system.
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addText(),
addItem(), addWidget()
*/
QGraphicsRectItem *QGraphicsScene::addRect(const QRectF &rect, const QPen &pen, const QBrush &brush)
{
QGraphicsRectItem *item = new QGraphicsRectItem(rect);
item->setPen(pen);
item->setBrush(brush);
addItem(item);
return item;
}
/*!
\fn QGraphicsRectItem *QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
\since 4.3
This convenience function is equivalent to calling addRect(QRectF(\a x,
\a y, \a w, \a h), \a pen, \a brush).
*/
/*!
Creates and adds a text item to the scene, and returns the item
pointer. The text string is initialized to \a text, and its font
is initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsTextItem *QGraphicsScene::addText(const QString &text, const QFont &font)
{
QGraphicsTextItem *item = new QGraphicsTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates and adds a QGraphicsSimpleTextItem to the scene, and returns the
item pointer. The text string is initialized to \a text, and its font is
initialized to \a font.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addItem(), addWidget()
*/
QGraphicsSimpleTextItem *QGraphicsScene::addSimpleText(const QString &text, const QFont &font)
{
QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem(text);
item->setFont(font);
addItem(item);
return item;
}
/*!
Creates a new QGraphicsProxyWidget for \a widget, adds it to the scene,
and returns a pointer to the proxy. \a wFlags set the default window flags
for the embedding proxy widget.
The item's position is initialized to (0, 0).
If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
QGraphicsScene will emit changed() once control goes back to the event
loop.
Note that widgets with the Qt::WA_PaintOnScreen widget attribute
set and widgets that wrap an external application or controller
are not supported. Examples are QGLWidget and QAxWidget.
\sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
addText(), addSimpleText(), addItem()
*/
QGraphicsProxyWidget *QGraphicsScene::addWidget(QWidget *widget, Qt::WindowFlags wFlags)
{
QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0, wFlags);
proxy->setWidget(widget);
addItem(proxy);
return proxy;
}
/*!
Removes the item \a item and all its children from the scene. The
ownership of \a item is passed on to the caller (i.e.,
QGraphicsScene will no longer delete \a item when destroyed).
\sa addItem()
*/
void QGraphicsScene::removeItem(QGraphicsItem *item)
{
// ### Refactoring: This function shares much functionality with _q_removeItemLater()
Q_D(QGraphicsScene);
if (!item) {
qWarning("QGraphicsScene::removeItem: cannot remove 0-item");
return;
}
if (item->scene() != this) {
qWarning("QGraphicsScene::removeItem: item %p's scene (%p)"
" is different from this scene (%p)",
item, item->scene(), this);
return;
}
// Notify the item that it's scene is changing to 0, allowing the item to
// react.
const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
qVariantFromValue<QGraphicsScene *>(0)));
QGraphicsScene *targetScene = qVariantValue<QGraphicsScene *>(newSceneVariant);
if (targetScene != 0 && targetScene != this) {
targetScene->addItem(item);
return;
}
// If the item has focus, remove it (and any focusWidget reference).
item->clearFocus();
// Clear its background
item->update();
// Note: This will access item's sceneBoundingRect(), which (as this is
// C++) is why we cannot call removeItem() from QGraphicsItem's
// destructor.
d->removeFromIndex(item);
if (item == d->tabFocusFirst) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
widget->d_func()->fixFocusChainBeforeReparenting(0, 0);
}
// Set the item's scene ptr to 0.
item->d_func()->scene = 0;
// Detach the item from its parent.
if (QGraphicsItem *parentItem = item->parentItem()) {
if (parentItem->scene()) {
Q_ASSERT_X(parentItem->scene() == this, "QGraphicsScene::removeItem",
"Parent item's scene is different from this item's scene");
item->setParentItem(0);
}
}
// Remove from our item lists.
int index = item->d_func()->index;
if (index != -1) {
d->freeItemIndexes << index;
d->indexedItems[index] = 0;
} else {
d->unindexedItems.removeAll(item);
}
// Remove from scene transform cache
int transformIndex = item->d_func()->sceneTransformIndex;
if (transformIndex != -1) {
d->validTransforms.setBit(transformIndex, 0);
d->freeSceneTransformSlots.append(transformIndex);
item->d_func()->sceneTransformIndex = -1;
}
if (item == d->focusItem)
d->focusItem = 0;
if (item == d->lastFocusItem)
d->lastFocusItem = 0;
if (item == d->activeWindow) {
// ### deactivate...
d->activeWindow = 0;
}
// Disable selectionChanged() for individual items
++d->selectionChanging;
int oldSelectedItemsSize = d->selectedItems.size();
// Update selected & hovered item bookkeeping
d->selectedItems.remove(item);
d->hoverItems.removeAll(item);
d->pendingUpdateItems.removeAll(item);
d->cachedItemsUnderMouse.removeAll(item);
d->unpolishedItems.removeAll(item);
d->dirtyItems.removeAll(item);
//We remove all references of item from the sceneEventFilter arrays
QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = d->sceneEventFilters.begin();
while (iterator != d->sceneEventFilters.end()) {
if (iterator.value() == item || iterator.key() == item)
iterator = d->sceneEventFilters.erase(iterator);
else
++iterator;
}
//Ensure dirty flag have the correct default value so the next time it will be added it will receive updates
item->d_func()->dirty = 0;
item->d_func()->dirtyChildren = 0;
// Remove all children recursively
foreach (QGraphicsItem *child, item->children())
removeItem(child);
// Reset the mouse grabber and focus item data.
if (d->mouseGrabberItems.contains(item))
d->ungrabMouse(item);
// Reset the keyboard grabber
if (d->keyboardGrabberItems.contains(item))
item->ungrabKeyboard();
// Reset the last mouse grabber item
if (item == d->lastMouseGrabberItem)
d->lastMouseGrabberItem = 0;
// Reenable selectionChanged() for individual items
--d->selectionChanging;
if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemsSize)
emit selectionChanged();
// Deliver post-change notification
item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
}
/*!
Returns the scene's current focus item, or 0 if no item currently has
focus.
The focus item receives keyboard input when the scene receives a
key event.
\sa setFocusItem(), QGraphicsItem::hasFocus()
*/
QGraphicsItem *QGraphicsScene::focusItem() const
{
Q_D(const QGraphicsScene);
return d->focusItem;
}
/*!
Sets the scene's focus item to \a item, with the focus reason \a
focusReason, after removing focus from any previous item that may have had
focus.
If \a item is 0, or if it either does not accept focus (i.e., it does not
have the QGraphicsItem::ItemIsFocusable flag enabled), or is not visible
or not enabled, this function only removes focus from any previous
focusitem.
If item is not 0, and the scene does not currently have focus (i.e.,
hasFocus() returns false), this function will call setFocus()
automatically.
\sa focusItem(), hasFocus(), setFocus()
*/
void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (item == d->focusItem)
return;
if (item && (!(item->flags() & QGraphicsItem::ItemIsFocusable)
|| !item->isVisible() || !item->isEnabled())) {
item = 0;
}
if (item) {
setFocus(focusReason);
if (item == d->focusItem)
return;
}
if (d->focusItem) {
QFocusEvent event(QEvent::FocusOut, focusReason);
d->lastFocusItem = d->focusItem;
d->focusItem = 0;
d->sendEvent(d->lastFocusItem, &event);
}
if (item) {
if (item->isWidget()) {
// Update focus child chain.
static_cast<QGraphicsWidget *>(item)->d_func()->setFocusWidget();
}
d->focusItem = item;
QFocusEvent event(QEvent::FocusIn, focusReason);
d->sendEvent(item, &event);
}
}
/*!
Returns true if the scene has focus; otherwise returns false. If the scene
has focus, it will will forward key events from QKeyEvent to any item that
has focus.
\sa setFocus(), setFocusItem()
*/
bool QGraphicsScene::hasFocus() const
{
Q_D(const QGraphicsScene);
return d->hasFocus;
}
/*!
Sets focus on the scene by sending a QFocusEvent to the scene, passing \a
focusReason as the reason. If the scene regains focus after having
previously lost it while an item had focus, the last focus item will
receive focus with \a focusReason as the reason.
If the scene already has focus, this function does nothing.
\sa hasFocus(), clearFocus(), setFocusItem()
*/
void QGraphicsScene::setFocus(Qt::FocusReason focusReason)
{
Q_D(QGraphicsScene);
if (d->hasFocus)
return;
QFocusEvent event(QEvent::FocusIn, focusReason);
QCoreApplication::sendEvent(this, &event);
}
/*!
Clears focus from the scene. If any item has focus when this function is
called, it will lose focus, and regain focus again once the scene regains
focus.
A scene that does not have focus ignores key events.
\sa hasFocus(), setFocus(), setFocusItem()
*/
void QGraphicsScene::clearFocus()
{
Q_D(QGraphicsScene);
if (d->hasFocus) {
d->hasFocus = false;
setFocusItem(0, Qt::OtherFocusReason);
}
}
/*!
\property QGraphicsScene::stickyFocus
\brief whether or not clicking the scene will clear focus
If this property is false (the default), then clicking on the scene
background or on an item that does not accept focus, will clear
focus. Otherwise, focus will remain unchanged.
The focus change happens in response to a mouse press. You can reimplement
mousePressEvent() in a subclass of QGraphicsScene to toggle this property
based on where the user has clicked.
\sa clearFocus(), setFocusItem()
*/
void QGraphicsScene::setStickyFocus(bool enabled)
{
Q_D(QGraphicsScene);
d->stickyFocus = enabled;
}
bool QGraphicsScene::stickyFocus() const
{
Q_D(const QGraphicsScene);
return d->stickyFocus;
}
/*!
Returns the current mouse grabber item, or 0 if no item is currently
grabbing the mouse. The mouse grabber item is the item that receives all
mouse events sent to the scene.
An item becomes a mouse grabber when it receives and accepts a
mouse press event, and it stays the mouse grabber until either of
the following events occur:
\list
\o If the item receives a mouse release event when there are no other
buttons pressed, it loses the mouse grab.
\o If the item becomes invisible (i.e., someone calls \c {item->setVisible(false))},
or if it becomes disabled (i.e., someone calls \c {item->setEnabled(false))},
it loses the mouse grab.
\o If the item is removed from the scene, it loses the mouse grab.
\endlist
If the item loses its mouse grab, the scene will ignore all mouse events
until a new item grabs the mouse (i.e., until a new item receives a mouse
press event).
*/
QGraphicsItem *QGraphicsScene::mouseGrabberItem() const
{
Q_D(const QGraphicsScene);
return !d->mouseGrabberItems.isEmpty() ? d->mouseGrabberItems.last() : 0;
}
/*!
\property QGraphicsScene::backgroundBrush
\brief the background brush of the scene.
Set this property to changes the scene's background to a different color,
gradient or texture. The default background brush is Qt::NoBrush. The
background is drawn before (behind) the items.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 3
QGraphicsScene::render() calls drawBackground() to draw the scene
background. For more detailed control over how the background is drawn,
you can reimplement drawBackground() in a subclass of QGraphicsScene.
*/
QBrush QGraphicsScene::backgroundBrush() const
{
Q_D(const QGraphicsScene);
return d->backgroundBrush;
}
void QGraphicsScene::setBackgroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->backgroundBrush = brush;
foreach (QGraphicsView *view, d->views) {
view->resetCachedContent();
view->viewport()->update();
}
update();
}
/*!
\property QGraphicsScene::foregroundBrush
\brief the foreground brush of the scene.
Change this property to set the scene's foreground to a different
color, gradient or texture.
The foreground is drawn after (on top of) the items. The default
foreground brush is Qt::NoBrush ( i.e. the foreground is not
drawn).
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 4
QGraphicsScene::render() calls drawForeground() to draw the scene
foreground. For more detailed control over how the foreground is
drawn, you can reimplement the drawForeground() function in a
QGraphicsScene subclass.
*/
QBrush QGraphicsScene::foregroundBrush() const
{
Q_D(const QGraphicsScene);
return d->foregroundBrush;
}
void QGraphicsScene::setForegroundBrush(const QBrush &brush)
{
Q_D(QGraphicsScene);
d->foregroundBrush = brush;
foreach (QGraphicsView *view, views())
view->viewport()->update();
update();
}
/*!
This method is used by input methods to query a set of properties of
the scene to be able to support complex input method operations as support
for surrounding text and reconversions.
The \a query parameter specifies which property is queried.
\sa QWidget::inputMethodQuery()
*/
QVariant QGraphicsScene::inputMethodQuery(Qt::InputMethodQuery query) const
{
Q_D(const QGraphicsScene);
if (!d->focusItem)
return QVariant();
const QTransform matrix = d->focusItem->sceneTransform();
QVariant value = d->focusItem->inputMethodQuery(query);
if (value.type() == QVariant::RectF)
value = matrix.mapRect(value.toRectF());
else if (value.type() == QVariant::PointF)
value = matrix.map(value.toPointF());
else if (value.type() == QVariant::Rect)
value = matrix.mapRect(value.toRect());
else if (value.type() == QVariant::Point)
value = matrix.map(value.toPoint());
return value;
}
/*!
\fn void QGraphicsScene::update(const QRectF &rect)
Schedules a redraw of the area \a rect on the scene.
\sa sceneRect(), changed()
*/
void QGraphicsScene::update(const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->updateAll || (rect.isEmpty() && !rect.isNull()))
return;
// Check if anyone's connected; if not, we can send updates directly to
// the views. Otherwise or if there are no views, use old behavior.
bool directUpdates = !(d->connectedSignals & d->changedSignalMask) && !d->views.isEmpty();
if (rect.isNull()) {
d->updateAll = true;
d->updatedRects.clear();
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i)
d->views.at(i)->d_func()->updateAll();
}
} else {
if (directUpdates) {
// Update all views.
for (int i = 0; i < d->views.size(); ++i) {
QGraphicsView *view = d->views.at(i);
view->d_func()->updateRegion(QRegion(view->mapFromScene(rect).boundingRect()));
}
} else {
d->updatedRects << rect;
}
}
if (!directUpdates && !d->calledEmitUpdated) {
d->calledEmitUpdated = true;
QMetaObject::invokeMethod(this, "_q_emitUpdated", Qt::QueuedConnection);
}
}
/*!
\fn void QGraphicsScene::update(qreal x, qreal y, qreal w, qreal h)
\overload
\since 4.3
This function is equivalent to calling update(QRectF(\a x, \a y, \a w,
\a h));
*/
/*!
Invalidates and schedules a redraw of the \a layers in \a rect on the
scene. Any cached content in \a layers is unconditionally invalidated and
redrawn.
You can use this function overload to notify QGraphicsScene of changes to
the background or the foreground of the scene. This function is commonly
used for scenes with tile-based backgrounds to notify changes when
QGraphicsView has enabled
\l{QGraphicsView::CacheBackground}{CacheBackground}.
Example:
\snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 5
Note that QGraphicsView currently supports background caching only (see
QGraphicsView::CacheBackground). This function is equivalent to calling
update() if any layer but BackgroundLayer is passed.
\sa QGraphicsView::resetCachedContent()
*/
void QGraphicsScene::invalidate(const QRectF &rect, SceneLayers layers)
{
foreach (QGraphicsView *view, views())
view->invalidateScene(rect, layers);
update(rect);
}
/*!
\fn void QGraphicsScene::invalidate(qreal x, qreal y, qreal w, qreal h, SceneLayers layers)
\overload
\since 4.3
This convenience function is equivalent to calling invalidate(QRectF(\a x, \a
y, \a w, \a h), \a layers);
*/
/*!
Returns a list of all the views that display this scene.
\sa QGraphicsView::scene()
*/
QList <QGraphicsView *> QGraphicsScene::views() const
{
Q_D(const QGraphicsScene);
return d->views;
}
/*!
This slot \e advances the scene by one step, by calling
QGraphicsItem::advance() for all items on the scene. This is done in two
phases: in the first phase, all items are notified that the scene is about
to change, and in the second phase all items are notified that they can
move. In the first phase, QGraphicsItem::advance() is called passing a
value of 0 as an argument, and 1 is passed in the second phase.
\sa QGraphicsItem::advance(), QGraphicsItemAnimation, QTimeLine
*/
void QGraphicsScene::advance()
{
for (int i = 0; i < 2; ++i) {
foreach (QGraphicsItem *item, items())
item->advance(i);
}
}
/*!
Processes the event \a event, and dispatches it to the respective
event handlers.
In addition to calling the convenience event handlers, this
function is responsible for converting mouse move events to hover
events for when there is no mouse grabber item. Hover events are
delivered directly to items; there is no convenience function for
them.
Unlike QWidget, QGraphicsScene does not have the convenience functions
\l{QWidget::}{enterEvent()} and \l{QWidget::}{leaveEvent()}. Use this
function to obtain those events instead.
\sa contextMenuEvent(), keyPressEvent(), keyReleaseEvent(),
mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(),
mouseDoubleClickEvent(), focusInEvent(), focusOutEvent()
*/
bool QGraphicsScene::event(QEvent *event)
{
Q_D(QGraphicsScene);
switch (event->type()) {
case QEvent::GraphicsSceneMousePress:
case QEvent::GraphicsSceneMouseMove:
case QEvent::GraphicsSceneMouseRelease:
case QEvent::GraphicsSceneMouseDoubleClick:
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
// Reset the under-mouse list to ensure that this event gets fresh
// item-under-mouse data. Be careful about this list; if people delete
// items from inside event handlers, this list can quickly end up
// having stale pointers in it. We need to clear it before dispatching
// events that use it.
d->cachedItemsUnderMouse.clear();
default:
break;
}
switch (event->type()) {
case QEvent::GraphicsSceneDragEnter:
dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragMove:
dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDragLeave:
dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneDrop:
dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
break;
case QEvent::GraphicsSceneContextMenu:
contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent *>(event));
break;
case QEvent::KeyPress:
if (!d->focusItem) {
QKeyEvent *k = static_cast<QKeyEvent *>(event);
if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
bool res = false;
if (k->key() == Qt::Key_Backtab
|| (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) {
res = focusNextPrevChild(false);
} else if (k->key() == Qt::Key_Tab) {
res = focusNextPrevChild(true);
}
if (!res)
event->ignore();
return true;
}
}
}
keyPressEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::KeyRelease:
keyReleaseEvent(static_cast<QKeyEvent *>(event));
break;
case QEvent::ShortcutOverride: {
QGraphicsItem *parent = focusItem();
while (parent) {
d->sendEvent(parent, event);
if (event->isAccepted())
return true;
parent = parent->parentItem();
}
}
return false;
case QEvent::GraphicsSceneMouseMove:
mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMousePress:
mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseRelease:
mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneMouseDoubleClick:
mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
break;
case QEvent::GraphicsSceneWheel:
wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event));
break;
case QEvent::FocusIn:
focusInEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::FocusOut:
focusOutEvent(static_cast<QFocusEvent *>(event));
break;
case QEvent::GraphicsSceneHoverEnter:
case QEvent::GraphicsSceneHoverLeave:
case QEvent::GraphicsSceneHoverMove:
d->dispatchHoverEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
break;
case QEvent::Leave:
d->leaveScene();
break;
case QEvent::GraphicsSceneHelp:
helpEvent(static_cast<QGraphicsSceneHelpEvent *>(event));
break;
case QEvent::InputMethod:
inputMethodEvent(static_cast<QInputMethodEvent *>(event));
break;
case QEvent::WindowActivate: {
if (!d->activationRefCount++) {
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
// Restore window activation.
QGraphicsItem *nextFocusItem = d->focusItem ? d->focusItem : d->lastFocusItem;
if (nextFocusItem && nextFocusItem->window())
setActiveWindow(static_cast<QGraphicsWidget *>(nextFocusItem));
else if (d->tabFocusFirst && d->tabFocusFirst->isWindow())
setActiveWindow(d->tabFocusFirst);
}
break;
}
case QEvent::WindowDeactivate: {
if (!--d->activationRefCount) {
// Remove window activation.
setActiveWindow(0);
// Notify all non-window widgets.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget() && item->isVisible() && !item->isWindow() && !item->parentWidget()) {
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(static_cast<QGraphicsWidget *>(item), &event);
}
}
}
break;
}
case QEvent::ApplicationFontChange: {
// Resolve the existing scene font.
d->resolveFont();
break;
}
case QEvent::FontChange:
// Update the entire scene when the font changes.
update();
break;
case QEvent::ApplicationPaletteChange: {
// Resolve the existing scene palette.
d->resolvePalette();
break;
}
case QEvent::PaletteChange:
// Update the entire scene when the palette changes.
update();
break;
case QEvent::StyleChange:
// Reresolve all widgets' styles. Update all top-level widgets'
// geometries that do not have an explicit style set.
update();
break;
case QEvent::Timer:
if (d->indexTimerId && static_cast<QTimerEvent *>(event)->timerId() == d->indexTimerId) {
if (d->restartIndexTimer) {
d->restartIndexTimer = false;
} else {
// this call will kill the timer
d->_q_updateIndex();
}
}
// Fallthrough intended - support timers in subclasses.
default:
return QObject::event(event);
}
return true;
}
/*!
\reimp
QGraphicsScene filters QApplication's events to detect palette and font
changes.
*/
bool QGraphicsScene::eventFilter(QObject *watched, QEvent *event)
{
if (watched != qApp)
return false;
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
qApp->postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
break;
case QEvent::ApplicationFontChange:
qApp->postEvent(this, new QEvent(QEvent::ApplicationFontChange));
break;
default:
break;
}
return false;
}
/*!
This event handler, for event \a contextMenuEvent, can be reimplemented in
a subclass to receive context menu events. The default implementation
forwards the event to the topmost item that accepts context menu events at
the position of the event. If no items accept context menu events at this
position, the event is ignored.
\sa QGraphicsItem::contextMenuEvent()
*/
void QGraphicsScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent)
{
Q_D(QGraphicsScene);
// Ignore by default.
contextMenuEvent->ignore();
// Send the event to all items at this position until one item accepts the
// event.
foreach (QGraphicsItem *item, d->itemsAtPosition(contextMenuEvent->screenPos(),
contextMenuEvent->scenePos(),
contextMenuEvent->widget())) {
contextMenuEvent->setPos(item->d_ptr->genericMapFromScene(contextMenuEvent->scenePos(),
contextMenuEvent->widget()));
contextMenuEvent->accept();
if (!d->sendEvent(item, contextMenuEvent))
break;
if (contextMenuEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag enter events for the scene.
The default implementation accepts the event and prepares the scene to
accept drag move events.
\sa QGraphicsItem::dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
d->dragDropItem = 0;
d->lastDropAction = Qt::IgnoreAction;
event->accept();
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag move events for the scene.
\sa QGraphicsItem::dragMoveEvent(), dragEnterEvent(), dragLeaveEvent(),
dropEvent()
*/
void QGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
event->ignore();
if (!d->mouseGrabberItems.isEmpty()) {
// Mouse grabbers that start drag events lose the mouse grab.
d->clearMouseGrabber();
d->mouseGrabberButtonDownPos.clear();
d->mouseGrabberButtonDownScenePos.clear();
d->mouseGrabberButtonDownScreenPos.clear();
}
bool eventDelivered = false;
// Find the topmost enabled items under the cursor. They are all
// candidates for accepting drag & drop events.
foreach (QGraphicsItem *item, d->itemsAtPosition(event->screenPos(),
event->scenePos(),
event->widget())) {
if (!item->isEnabled() || !item->acceptDrops())
continue;
if (item != d->dragDropItem) {
// Enter the new drag drop item. If it accepts the event, we send
// the leave to the parent item.
QGraphicsSceneDragDropEvent dragEnter(QEvent::GraphicsSceneDragEnter);
d->cloneDragDropEvent(&dragEnter, event);
dragEnter.setDropAction(event->proposedAction());
d->sendDragDropEvent(item, &dragEnter);
event->setAccepted(dragEnter.isAccepted());
event->setDropAction(dragEnter.dropAction());
if (!event->isAccepted()) {
// Propagate to the item under
continue;
}
d->lastDropAction = event->dropAction();
if (d->dragDropItem) {
// Leave the last drag drop item. A perfect implementation
// would set the position of this event to the point where
// this event and the last event intersect with the item's
// shape, but that's not easy to do. :-)
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
}
// We've got a new drag & drop item
d->dragDropItem = item;
}
// Send the move event.
event->setDropAction(d->lastDropAction);
event->accept();
d->sendDragDropEvent(item, event);
if (event->isAccepted())
d->lastDropAction = event->dropAction();
eventDelivered = true;
break;
}
if (!eventDelivered) {
if (d->dragDropItem) {
// Leave the last drag drop item
QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
d->cloneDragDropEvent(&dragLeave, event);
d->sendDragDropEvent(d->dragDropItem, &dragLeave);
d->dragDropItem = 0;
}
// Propagate
event->setDropAction(Qt::IgnoreAction);
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drag leave events for the scene.
\sa QGraphicsItem::dragLeaveEvent(), dragEnterEvent(), dragMoveEvent(),
dropEvent()
*/
void QGraphicsScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Leave the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a subclass
to receive drop events for the scene.
\sa QGraphicsItem::dropEvent(), dragEnterEvent(), dragMoveEvent(),
dragLeaveEvent()
*/
void QGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
Q_D(QGraphicsScene);
if (d->dragDropItem) {
// Drop on the last drag drop item
d->sendDragDropEvent(d->dragDropItem, event);
d->dragDropItem = 0;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus in events.
The default implementation sets focus on the scene, and then on the last
focus item.
\sa QGraphicsItem::focusOutEvent()
*/
void QGraphicsScene::focusInEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = true;
switch (focusEvent->reason()) {
case Qt::TabFocusReason:
if (!focusNextPrevChild(true))
focusEvent->ignore();
break;
case Qt::BacktabFocusReason:
if (!focusNextPrevChild(false))
focusEvent->ignore();
break;
default:
if (d->lastFocusItem) {
// Set focus on the last focus item
setFocusItem(d->lastFocusItem, focusEvent->reason());
}
break;
}
}
/*!
This event handler, for event \a focusEvent, can be reimplemented in a
subclass to receive focus out events.
The default implementation removes focus from any focus item, then removes
focus from the scene.
\sa QGraphicsItem::focusInEvent()
*/
void QGraphicsScene::focusOutEvent(QFocusEvent *focusEvent)
{
Q_D(QGraphicsScene);
d->hasFocus = false;
setFocusItem(0, focusEvent->reason());
// Remove all popups when the scene loses focus.
if (!d->popupWidgets.isEmpty())
d->removePopup(d->popupWidgets.first());
}
/*!
This event handler, for event \a helpEvent, can be
reimplemented in a subclass to receive help events. The events
are of type QEvent::ToolTip, which are created when a tooltip is
requested.
The default implementation shows the tooltip of the topmost
item, i.e., the item with the highest z-value, at the mouse
cursor position. If no item has a tooltip set, this function
does nothing.
\sa QGraphicsItem::toolTip(), QGraphicsSceneHelpEvent
*/
void QGraphicsScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent)
{
#ifdef QT_NO_TOOLTIP
Q_UNUSED(helpEvent);
#else
// Find the first item that does tooltips
Q_D(QGraphicsScene);
QList<QGraphicsItem *> itemsAtPos = d->itemsAtPosition(helpEvent->screenPos(),
helpEvent->scenePos(),
helpEvent->widget());
QGraphicsItem *toolTipItem = 0;
for (int i = 0; i < itemsAtPos.size(); ++i) {
QGraphicsItem *tmp = itemsAtPos.at(i);
if (!tmp->toolTip().isEmpty()) {
toolTipItem = tmp;
break;
}
}
// Show or hide the tooltip
QString text;
QPoint point;
if (toolTipItem && !toolTipItem->toolTip().isEmpty()) {
text = toolTipItem->toolTip();
point = helpEvent->screenPos();
}
QToolTip::showText(point, text);
helpEvent->setAccepted(!text.isEmpty());
#endif
}
bool QGraphicsScenePrivate::itemAcceptsHoverEvents_helper(const QGraphicsItem *item) const
{
return item->acceptHoverEvents()
|| (item->isWidget() && static_cast<const QGraphicsWidget *>(item)->d_func()->hasDecoration());
}
/*!
This event handler, for event \a hoverEvent, can be reimplemented in a
subclass to receive hover enter events. The default implementation
forwards the event to the topmost item that accepts hover events at the
scene position from the event.
\sa QGraphicsItem::hoverEvent(), QGraphicsItem::setAcceptHoverEvents()
*/
bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEvent)
{
// Find the first item that accepts hover events, reusing earlier
// calculated data is possible.
if (cachedItemsUnderMouse.isEmpty()) {
cachedItemsUnderMouse = itemsAtPosition(hoverEvent->screenPos(),
hoverEvent->scenePos(),
hoverEvent->widget());
}
QGraphicsItem *item = 0;
for (int i = 0; i < cachedItemsUnderMouse.size(); ++i) {
QGraphicsItem *tmp = cachedItemsUnderMouse.at(i);
if (itemAcceptsHoverEvents_helper(tmp)) {
item = tmp;
break;
}
}
// Find the common ancestor item for the new topmost hoverItem and the
// last item in the hoverItem list.
QGraphicsItem *commonAncestorItem = (item && !hoverItems.isEmpty()) ? item->commonAncestorItem(hoverItems.last()) : 0;
while (commonAncestorItem && !itemAcceptsHoverEvents_helper(commonAncestorItem))
commonAncestorItem = commonAncestorItem->parentItem();
if (commonAncestorItem && commonAncestorItem->window() != item->window()) {
// The common ancestor isn't in the same window as the two hovered
// items.
commonAncestorItem = 0;
}
// Check if the common ancestor item is known.
int index = commonAncestorItem ? hoverItems.indexOf(commonAncestorItem) : -1;
// Send hover leaves to any existing hovered children of the common
// ancestor item.
for (int i = hoverItems.size() - 1; i > index; --i) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (itemAcceptsHoverEvents_helper(lastItem))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, hoverEvent);
}
// Item is a child of a known item. Generate enter events for the
// missing links.
QList<QGraphicsItem *> parents;
QGraphicsItem *parent = item;
while (parent && parent != commonAncestorItem) {
parents.prepend(parent);
if (parent->isWindow()) {
// Stop at the window - we don't deliver beyond this point.
break;
}
parent = parent->parentItem();
}
for (int i = 0; i < parents.size(); ++i) {
parent = parents.at(i);
hoverItems << parent;
if (itemAcceptsHoverEvents_helper(parent))
sendHoverEvent(QEvent::GraphicsSceneHoverEnter, parent, hoverEvent);
}
// Generate a move event for the item itself
if (item && !hoverItems.isEmpty() && item == hoverItems.last()) {
sendHoverEvent(QEvent::GraphicsSceneHoverMove, item, hoverEvent);
return true;
}
return false;
}
/*!
\internal
Handles all actions necessary to clean up the scene when the mouse leaves
the view.
*/
void QGraphicsScenePrivate::leaveScene()
{
Q_Q(QGraphicsScene);
#ifndef QT_NO_TOOLTIP
// Remove any tooltips
QToolTip::showText(QPoint(), QString());
#endif
// Send HoverLeave events to all existing hover items, topmost first.
QGraphicsView *senderWidget = qobject_cast<QGraphicsView *>(q->sender());
QGraphicsSceneHoverEvent hoverEvent;
hoverEvent.setWidget(senderWidget);
if (senderWidget) {
QPoint cursorPos = QCursor::pos();
hoverEvent.setScenePos(senderWidget->mapToScene(senderWidget->mapFromGlobal(cursorPos)));
hoverEvent.setLastScenePos(hoverEvent.scenePos());
hoverEvent.setScreenPos(cursorPos);
hoverEvent.setLastScreenPos(hoverEvent.screenPos());
}
while (!hoverItems.isEmpty()) {
QGraphicsItem *lastItem = hoverItems.takeLast();
if (lastItem->acceptHoverEvents()
|| (lastItem->isWidget() && static_cast<QGraphicsWidget*>(lastItem)->d_func()->hasDecoration()))
sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, &hoverEvent);
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive keypress events. The default implementation forwards
the event to current focus item.
\sa QGraphicsItem::keyPressEvent(), focusItem()
*/
void QGraphicsScene::keyPressEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyReleaseEvent; they are identical
// ### (except this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a keyEvent, can be reimplemented in a
subclass to receive key release events. The default implementation
forwards the event to current focus item.
\sa QGraphicsItem::keyReleaseEvent(), focusItem()
*/
void QGraphicsScene::keyReleaseEvent(QKeyEvent *keyEvent)
{
// ### Merge this function with keyPressEvent; they are identical (except
// ### this comment).
Q_D(QGraphicsScene);
QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
if (!item)
item = focusItem();
if (item) {
QGraphicsItem *p = item;
do {
// Accept the event by default
keyEvent->accept();
// Send it; QGraphicsItem::keyPressEvent ignores it. If the event
// is filtered out, stop propagating it.
if (!d->sendEvent(p, keyEvent))
break;
} while (!keyEvent->isAccepted() && !p->isWindow() && (p = p->parentItem()));
} else {
keyEvent->ignore();
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse press events for the scene.
The default implementation depends on the state of the scene. If
there is a mouse grabber item, then the event is sent to the mouse
grabber. Otherwise, it is forwarded to the topmost item that
accepts mouse events at the scene position from the event, and
that item promptly becomes the mouse grabber item.
If there is no item at the given position on the scene, the
selection area is reset, any focus item loses its input focus, and
the event is then ignored.
\sa QGraphicsItem::mousePressEvent(),
QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse move events for the scene.
The default implementation depends on the mouse grabber state. If there is
a mouse grabber item, the event is sent to the mouse grabber. If there
are any items that accept hover events at the current position, the event
is translated into a hover event and accepted; otherwise it's ignored.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseReleaseEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
if (mouseEvent->buttons())
return;
QGraphicsSceneHoverEvent hover;
_q_hoverFromMouseEvent(&hover, mouseEvent);
mouseEvent->setAccepted(d->dispatchHoverEvent(&hover));
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse release events for the scene.
The default implementation depends on the mouse grabber state. If
there is no mouse grabber, the event is ignored. Otherwise, if
there is a mouse grabber item, the event is sent to the mouse
grabber. If this mouse release represents the last pressed button
on the mouse, the mouse grabber item then loses the mouse grab.
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
if (d->mouseGrabberItems.isEmpty()) {
mouseEvent->ignore();
return;
}
// Forward the event to the mouse grabber
d->sendMouseEvent(mouseEvent);
mouseEvent->accept();
// Reset the mouse grabber when the last mouse button has been released.
if (!mouseEvent->buttons()) {
if (!d->mouseGrabberItems.isEmpty()) {
d->lastMouseGrabberItem = d->mouseGrabberItems.last();
if (d->lastMouseGrabberItemHasImplicitMouseGrab)
d->mouseGrabberItems.last()->ungrabMouse();
} else {
d->lastMouseGrabberItem = 0;
}
// Generate a hoverevent
QGraphicsSceneHoverEvent hoverEvent;
_q_hoverFromMouseEvent(&hoverEvent, mouseEvent);
d->dispatchHoverEvent(&hoverEvent);
}
}
/*!
This event handler, for event \a mouseEvent, can be reimplemented
in a subclass to receive mouse doubleclick events for the scene.
If someone doubleclicks on the scene, the scene will first receive
a mouse press event, followed by a release event (i.e., a click),
then a doubleclick event, and finally a release event. If the
doubleclick event is delivered to a different item than the one
that received the first press and release, it will be delivered as
a press event. However, tripleclick events are not delivered as
doubleclick events in this case.
The default implementation is similar to mousePressEvent().
\sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
QGraphicsItem::mouseReleaseEvent(), QGraphicsItem::setAcceptedMouseButtons()
*/
void QGraphicsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
Q_D(QGraphicsScene);
d->mousePressEventHandler(mouseEvent);
}
/*!
This event handler, for event \a wheelEvent, can be reimplemented in a
subclass to receive mouse wheel events for the scene.
By default, the event is delivered to the topmost visible item under the
cursor. If ignored, the event propagates to the item beneath, and again
until the event is accepted, or it reaches the scene. If no items accept
the event, it is ignored.
\sa QGraphicsItem::wheelEvent()
*/
void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
{
Q_D(QGraphicsScene);
QList<QGraphicsItem *> wheelCandidates = d->itemsAtPosition(wheelEvent->screenPos(),
wheelEvent->scenePos(),
wheelEvent->widget());
bool hasSetFocus = false;
foreach (QGraphicsItem *item, wheelCandidates) {
if (!hasSetFocus && item->isEnabled() && (item->flags() & QGraphicsItem::ItemIsFocusable)) {
if (item->isWidget() && static_cast<QGraphicsWidget *>(item)->focusPolicy() == Qt::WheelFocus) {
hasSetFocus = true;
if (item != focusItem())
setFocusItem(item, Qt::MouseFocusReason);
}
}
wheelEvent->setPos(item->d_ptr->genericMapFromScene(wheelEvent->scenePos(),
wheelEvent->widget()));
wheelEvent->accept();
bool isWindow = item->isWindow();
d->sendEvent(item, wheelEvent);
if (isWindow || wheelEvent->isAccepted())
break;
}
}
/*!
This event handler, for event \a event, can be reimplemented in a
subclass to receive input method events for the scene.
The default implementation forwards the event to the focusItem().
If no item currently has focus, this function does nothing.
\sa QGraphicsItem::inputMethodEvent()
*/
void QGraphicsScene::inputMethodEvent(QInputMethodEvent *event)
{
Q_D(QGraphicsScene);
if (!d->focusItem)
return;
d->sendEvent(d->focusItem, event);
}
/*!
Draws the background of the scene using \a painter, before any items and
the foreground are drawn. Reimplement this function to provide a custom
background for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture, or gradient for the
background, you can call setBackgroundBrush() instead.
\sa drawForeground(), drawItems()
*/
void QGraphicsScene::drawBackground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->backgroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, backgroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
/*!
Draws the foreground of the scene using \a painter, after the background
and all items have been drawn. Reimplement this function to provide a
custom foreground for the scene.
All painting is done in \e scene coordinates. The \a rect
parameter is the exposed rectangle.
If all you want is to define a color, texture or gradient for the
foreground, you can call setForegroundBrush() instead.
\sa drawBackground(), drawItems()
*/
void QGraphicsScene::drawForeground(QPainter *painter, const QRectF &rect)
{
Q_D(QGraphicsScene);
if (d->foregroundBrush.style() != Qt::NoBrush) {
if (d->painterStateProtection)
painter->save();
painter->setBrushOrigin(0, 0);
painter->fillRect(rect, foregroundBrush());
if (d->painterStateProtection)
painter->restore();
}
}
static void _q_paintItem(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool useWindowOpacity, bool painterStateProtection)
{
if (!item->isWidget()) {
item->paint(painter, option, widget);
return;
}
QGraphicsWidget *widgetItem = static_cast<QGraphicsWidget *>(item);
QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(widgetItem);
const qreal windowOpacity = (proxy && proxy->widget() && useWindowOpacity)
? proxy->widget()->windowOpacity() : 1.0;
const qreal oldPainterOpacity = painter->opacity();
if (qFuzzyCompare(windowOpacity + 1, qreal(1.0)))
return;
// Set new painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity * windowOpacity);
// set layoutdirection on the painter
Qt::LayoutDirection oldLayoutDirection = painter->layoutDirection();
painter->setLayoutDirection(widgetItem->layoutDirection());
if (widgetItem->isWindow() && widgetItem->windowType() != Qt::Popup && widgetItem->windowType() != Qt::ToolTip
&& !(widgetItem->windowFlags() & Qt::FramelessWindowHint)) {
if (painterStateProtection)
painter->save();
widgetItem->paintWindowFrame(painter, option, widget);
if (painterStateProtection)
painter->restore();
}
widgetItem->paint(painter, option, widget);
// Restore layoutdirection on the painter.
painter->setLayoutDirection(oldLayoutDirection);
// Restore painter opacity.
if (windowOpacity < 1.0)
painter->setOpacity(oldPainterOpacity);
}
static void _q_paintIntoCache(QPixmap *pix, QGraphicsItem *item, const QRegion &pixmapExposed,
const QTransform &itemToPixmap, QPainter::RenderHints renderHints,
const QStyleOptionGraphicsItem *option, bool painterStateProtection)
{
QPixmap subPix;
QPainter pixmapPainter;
QRect br = pixmapExposed.boundingRect();
// Don't use subpixmap if we get a full update.
if (pixmapExposed.isEmpty() || (pixmapExposed.numRects() == 1 && br.contains(pix->rect()))) {
pix->fill(Qt::transparent);
pixmapPainter.begin(pix);
} else {
subPix = QPixmap(br.size());
subPix.fill(Qt::transparent);
pixmapPainter.begin(&subPix);
pixmapPainter.translate(-br.topLeft());
if (!pixmapExposed.isEmpty()) {
// Applied to subPix; paint is adjusted to the coordinate space is
// correct.
pixmapPainter.setClipRegion(pixmapExposed);
}
}
pixmapPainter.setRenderHints(pixmapPainter.renderHints(), false);
pixmapPainter.setRenderHints(renderHints, true);
pixmapPainter.setWorldTransform(itemToPixmap, true);
// Render.
_q_paintItem(item, &pixmapPainter, option, 0, false, painterStateProtection);
pixmapPainter.end();
if (!subPix.isNull()) {
// Blit the subpixmap into the main pixmap.
pixmapPainter.begin(pix);
pixmapPainter.setCompositionMode(QPainter::CompositionMode_Source);
pixmapPainter.setClipRegion(pixmapExposed);
pixmapPainter.drawPixmap(br.topLeft(), subPix);
pixmapPainter.end();
}
}
/*!
\internal
Draws items directly, or using cache.
*/
void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget,
bool painterStateProtection)
{
QGraphicsItemPrivate *itemd = item->d_ptr;
QGraphicsItem::CacheMode cacheMode = QGraphicsItem::CacheMode(itemd->cacheMode);
// Render directly, using no cache.
if (cacheMode == QGraphicsItem::NoCache
#ifdef Q_WS_X11
|| !X11->use_xrender
#endif
) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget, true, painterStateProtection);
return;
}
const qreal oldPainterOpacity = painter->opacity();
qreal newPainterOpacity = oldPainterOpacity;
QGraphicsProxyWidget *proxy = item->isWidget() ? qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(item)) : 0;
if (proxy && proxy->widget()) {
const qreal windowOpacity = proxy->widget()->windowOpacity();
if (windowOpacity < 1.0)
newPainterOpacity *= windowOpacity;
}
// Item's (local) bounding rect
QRectF brect = item->boundingRect();
QRectF adjustedBrect(brect);
_q_adjustRect(&adjustedBrect);
if (adjustedBrect.isEmpty())
return;
// Fetch the off-screen transparent buffer and exposed area info.
QString pixmapKey;
QPixmap pix;
QGraphicsItemCache *itemCache = itemd->extraItemCache();
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
if (itemCache->boundingRect != brect.toRect()) {
itemCache->boundingRect = brect.toRect();
itemCache->allExposed = true;
itemCache->exposed.clear();
}
pixmapKey = itemCache->key;
} else {
if ((pixmapKey = itemCache->deviceData.value(widget).key).isEmpty()) {
pixmapKey.sprintf("qgv-%p-%p", item, widget);
QGraphicsItemCache::DeviceData data;
data.key = pixmapKey;
itemCache->deviceData.insert(widget, data);
}
}
// Find pixmap in cache.
if (!itemCache->allExposed)
QPixmapCache::find(pixmapKey, pix);
// Render using item coordinate cache mode.
if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
QSize pixmapSize;
bool fixedCacheSize = false;
QRectF brectAligned = brect.toAlignedRect();
if ((fixedCacheSize = itemCache->fixedSize.isValid())) {
pixmapSize = itemCache->fixedSize;
} else {
pixmapSize = brectAligned.size().toSize();
}
// Create or recreate the pixmap.
int adjust = itemCache->fixedSize.isValid() ? 0 : 2;
QSize adjustSize(adjust*2, adjust*2);
QRectF br = brectAligned.adjusted(-adjust, -adjust, adjust, adjust);
if (pix.isNull() || (!fixedCacheSize && (pixmapSize + adjustSize) != pix.size())) {
pix = QPixmap(pixmapSize + adjustSize);
itemCache->exposed.clear();
itemCache->allExposed = true;
}
// Redraw any newly exposed areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty()) {
// Fit the item's bounding rect into the pixmap's coordinates.
QTransform itemToPixmap;
if (fixedCacheSize) {
const QPointF scale(pixmapSize.width() / brect.width(), pixmapSize.height() / brect.height());
itemToPixmap.scale(scale.x(), scale.y());
}
itemToPixmap.translate(-br.x(), -br.y());
// Generate the item's exposedRect and map its list of expose
// rects to device coordinates.
QStyleOptionGraphicsItem cacheOption = *option;
QRegion pixmapExposed;
QRectF exposedRect;
if (!itemCache->allExposed) {
for (int i = 0; i < itemCache->exposed.size(); ++i) {
QRectF r = itemCache->exposed.at(i);
exposedRect |= r;
pixmapExposed += itemToPixmap.mapRect(r).toAlignedRect();
}
} else {
exposedRect = brect;
}
cacheOption.exposedRect = exposedRect;
// Render.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&cacheOption, painterStateProtection);
// Reinsert this pixmap into the cache.
QPixmapCache::insert(pixmapKey, pix);
// Reset expose data.
itemCache->allExposed = false;
itemCache->exposed.clear();
}
// Redraw the exposed area using the transformed painter. Depending on
// the hardware, this may be a server-side operation, or an expensive
// qpixmap-image-transform-pixmap roundtrip.
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(br, pix, QRectF(QPointF(), pix.size()));
}
return;
}
// Render using device coordinate cache mode.
if (cacheMode == QGraphicsItem::DeviceCoordinateCache) {
// Find the item's bounds in device coordinates.
QRectF deviceBounds = painter->worldTransform().mapRect(brect);
QRect deviceRect = deviceBounds.toRect().adjusted(-1, -1, 1, 1);
if (deviceRect.isEmpty())
return;
QRect viewRect = widget ? widget->rect() : QRect();
if (widget && !viewRect.intersects(deviceRect))
return;
// Resort to direct rendering if the device rect exceeds the
// (optional) maximum bounds. (QGraphicsSvgItem uses this).
QSize maximumCacheSize =
itemd->extra(QGraphicsItemPrivate::ExtraMaxDeviceCoordCacheSize).toSize();
if (!maximumCacheSize.isEmpty()
&& (deviceRect.width() > maximumCacheSize.width()
|| deviceRect.height() > maximumCacheSize.height())) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget,
oldPainterOpacity != newPainterOpacity, painterStateProtection);
return;
}
// Create or reuse offscreen pixmap, possibly scroll/blit from the old one.
bool pixModified = false;
QGraphicsItemCache::DeviceData *deviceData = &itemCache->deviceData[widget];
bool invertable = true;
QTransform diff = deviceData->lastTransform.inverted(&invertable);
if (invertable)
diff *= painter->worldTransform();
deviceData->lastTransform = painter->worldTransform();
if (!invertable || diff.type() > QTransform::TxTranslate) {
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
pix = QPixmap();
}
// ### This is a pretty bad way to determine when to start partial
// exposure for DeviceCoordinateCache but it's the least intrusive
// approach for now.
#if 0
// Only if the device rect isn't fully contained.
bool allowPartialCacheExposure = !viewRect.contains(deviceRect);
#else
// Only if deviceRect is 20% taller or wider than the desktop.
QRect desktopRect = qApp->desktop()->availableGeometry(widget);
bool allowPartialCacheExposure = (desktopRect.width() * 1.2 < deviceRect.width()
|| desktopRect.height() * 1.2 < deviceRect.height());
#endif
QRegion scrollExposure;
if (deviceData->cacheIndent != QPoint() || allowPartialCacheExposure) {
// Part of pixmap is drawn. Either device contains viewrect (big
// item covers whole screen) or parts of device are outside the
// viewport. In either case the device rect must be the intersect
// between the two.
int dx = deviceRect.left() < viewRect.left() ? viewRect.left() - deviceRect.left() : 0;
int dy = deviceRect.top() < viewRect.top() ? viewRect.top() - deviceRect.top() : 0;
QPoint newCacheIndent(dx, dy);
deviceRect &= viewRect;
if (pix.isNull()) {
deviceData->cacheIndent = QPoint();
itemCache->allExposed = true;
itemCache->exposed.clear();
pixModified = true;
}
// Copy / "scroll" the old pixmap onto the new ole and calculate
// scrolled exposure.
if (newCacheIndent != deviceData->cacheIndent || deviceRect.size() != pix.size()) {
QPoint diff = newCacheIndent - deviceData->cacheIndent;
QPixmap newPix(deviceRect.size());
if (!pix.isNull()) {
QPainter newPixPainter(&newPix);
newPixPainter.setCompositionMode(QPainter::CompositionMode_Source);
newPixPainter.drawPixmap(-diff, pix);
newPixPainter.end();
}
QRegion exposed;
exposed += newPix.rect();
if (!pix.isNull())
exposed -= QRect(-diff, pix.size());
scrollExposure = exposed;
pix = newPix;
pixModified = true;
}
deviceData->cacheIndent = newCacheIndent;
} else {
// Full pixmap is drawn.
deviceData->cacheIndent = QPoint();
// Auto-adjust the pixmap size.
if (deviceRect.size() != pix.size()) {
// exposed needs to cover the whole pixmap
pix = QPixmap(deviceRect.size());
pixModified = true;
itemCache->allExposed = true;
itemCache->exposed.clear();
}
}
// Check for newly invalidated areas.
if (itemCache->allExposed || !itemCache->exposed.isEmpty() || !scrollExposure.isEmpty()) {
// Construct an item-to-pixmap transform.
QPointF p = deviceRect.topLeft();
QTransform itemToPixmap = painter->worldTransform();
if (!p.isNull())
itemToPixmap *= QTransform::fromTranslate(-p.x(), -p.y());
// Map the item's logical expose to pixmap coordinates.
QRegion pixmapExposed = scrollExposure;
if (!itemCache->allExposed) {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
pixmapExposed += itemToPixmap.mapRect(exposed.at(i)).toRect().adjusted(-1, -1, 1, 1);
}
// Calculate the style option's exposedRect.
QRectF br;
if (itemCache->allExposed) {
br = item->boundingRect();
} else {
const QVector<QRectF> &exposed = itemCache->exposed;
for (int i = 0; i < exposed.size(); ++i)
br |= exposed.at(i);
QTransform pixmapToItem = itemToPixmap.inverted();
foreach (QRect r, scrollExposure.rects())
br |= pixmapToItem.mapRect(r);
}
QStyleOptionGraphicsItem cacheOption = *option;
cacheOption.exposedRect = br.adjusted(-1, -1, 1, 1);
// Render the exposed areas.
_q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
&cacheOption, painterStateProtection);
// Reset expose data.
pixModified = true;
itemCache->allExposed = false;
itemCache->exposed.clear();
}
if (pixModified) {
// Reinsert this pixmap into the cache
QPixmapCache::insert(pixmapKey, pix);
}
// Redraw the exposed area using an untransformed painter. This
// effectively becomes a bitblit that does not transform the cache.
QTransform restoreTransform = painter->worldTransform();
painter->setWorldTransform(QTransform());
if (newPainterOpacity != oldPainterOpacity) {
painter->setOpacity(newPainterOpacity);
painter->drawPixmap(deviceRect.topLeft(), pix);
painter->setOpacity(oldPainterOpacity);
} else {
painter->drawPixmap(deviceRect.topLeft(), pix);
}
painter->setWorldTransform(restoreTransform);
return;
}
}
/*!
Paints the given \a items using the provided \a painter, after the
background has been drawn, and before the foreground has been
drawn. All painting is done in \e scene coordinates. Before
drawing each item, the painter must be transformed using
QGraphicsItem::sceneMatrix().
The \a options parameter is the list of style option objects for
each item in \a items. The \a numItems parameter is the number of
items in \a items and options in \a options. The \a widget
parameter is optional; if specified, it should point to the widget
that is being painted on.
The default implementation prepares the painter matrix, and calls
QGraphicsItem::paint() on all items. Reimplement this function to
provide custom painting of all items for the scene; gaining
complete control over how each item is drawn. In some cases this
can increase drawing performance significantly.
Example:
\snippet doc/src/snippets/graphicssceneadditemsnippet.cpp 0
\sa drawBackground(), drawForeground()
*/
void QGraphicsScene::drawItems(QPainter *painter,
int numItems,
QGraphicsItem *items[],
const QStyleOptionGraphicsItem options[], QWidget *widget)
{
Q_D(QGraphicsScene);
// Detect if painter state protection is disabled.
QTransform viewTransform = painter->worldTransform();
QVarLengthArray<QGraphicsItem *, 16> childClippers;
for (int i = 0; i < numItems; ++i) {
QGraphicsItem *item = items[i];
if (!(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
if (!childClippers.isEmpty()) {
// Item is not clipped to any ancestor: pop all current clippers.
for (int i = 0; i < childClippers.size(); ++i)
painter->restore();
childClippers.clear();
}
} else {
// Item is clipped to an ancestor, which may or may not be in our
// child clipper list. Let's start by finding the item's closest
// clipping ancestor.
QGraphicsItem *clipParent = item->parentItem();
while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape))
clipParent = clipParent->parentItem();
// Pop any in-between clippers. If the clipper is unknown, pop
// them all. ### QVarLengthArray::lastIndexOf().
int index = -1;
for (int n = childClippers.size() - 1; n >= 0; --n) {
if (childClippers[n] == clipParent) {
index = n;
break;
}
}
if (index != -1) {
int toPop = childClippers.size() - index - 1;
if (toPop > 0) {
for (int i = 0; i < toPop; ++i)
painter->restore();
childClippers.resize(index + 1);
}
}
// Sanity check
if (!childClippers.isEmpty())
Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent);
// If the clipper list is empty at this point, but we're still
// clipped to an ancestor, then we need to build the clip chain
// ourselves. There is only one case that can produce this issue:
// This item is stacked behind an ancestor:
// ItemStacksBehindParent.
if (childClippers.isEmpty()) {
Q_ASSERT(clipParent != 0);
// Build a stack of clippers.
QVarLengthArray<QGraphicsItem *, 16> clippers;
QGraphicsItem *p = clipParent;
do {
if (p->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)
clippers.append(p);
} while ((p = p->parentItem()) && (p->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren));
// ### This code path can also use the itemTransform
// optimization, but it's hit very rarely.
for (int i = clippers.size() - 1; i >= 0; --i) {
QGraphicsItem *clipper = clippers[i];
if (clipper->d_ptr->itemIsUntransformable()) {
painter->setWorldTransform(clipper->deviceTransform(viewTransform), false);
} else {
painter->setWorldTransform(clipper->sceneTransform() * viewTransform, false);
}
childClippers.append(clipper);
painter->save();
painter->setClipPath(clipper->shape(), Qt::IntersectClip);
}
Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent);
}
}
// Set up the painter transform
if (item->d_ptr->itemIsUntransformable()) {
painter->setWorldTransform(item->deviceTransform(viewTransform), false);
} else {
painter->setWorldTransform(item->sceneTransform() * viewTransform, false);
}
// Save painter
bool saveState = (d->painterStateProtection || (item->flags() & QGraphicsItem::ItemClipsToShape));
if (saveState)
painter->save();
// Set local clip
if (item->flags() & QGraphicsItem::ItemClipsToShape)
painter->setClipPath(item->shape(), Qt::IntersectClip);
// Setup opacity
painter->setOpacity(item->effectiveOpacity());
// Draw the item
d->drawItemHelper(item, painter, &options[i], widget, d->painterStateProtection);
if (saveState)
painter->restore();
if (item->flags() & QGraphicsItem::ItemClipsChildrenToShape) {
// Clip descendents to this item's shape, and keep the painter
// saved.
childClippers.append(item);
painter->save();
painter->setClipPath(item->shape(), Qt::IntersectClip);
}
}
for (int i = 0; i < childClippers.size(); ++i)
painter->restore();
painter->setWorldTransform(viewTransform);
}
/*!
\since 4.4
Finds a new widget to give the keyboard focus to, as appropriate for Tab
and Shift+Tab, and returns true if it can find a new widget, or false if
it cannot. If \a next is true, this function searches forward; if \a next
is false, it searches backward.
You can reimplement this function in a subclass of QGraphicsScene to
provide fine-grained control over how tab focus passes inside your
scene. The default implementation is based on the tab focus chain defined
by QGraphicsWidget::setTabOrder().
*/
bool QGraphicsScene::focusNextPrevChild(bool next)
{
Q_D(QGraphicsScene);
QGraphicsItem *item = focusItem();
if (item && !item->isWidget()) {
// Tab out of the scene.
return false;
}
if (!item) {
if (d->lastFocusItem && !d->lastFocusItem->isWidget()) {
// Restore focus to the last focusable non-widget item that had
// focus.
setFocusItem(d->lastFocusItem, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
}
if (!d->tabFocusFirst) {
// No widgets...
return false;
}
// The item must be a widget.
QGraphicsWidget *widget = 0;
if (!item) {
widget = next ? d->tabFocusFirst : d->tabFocusFirst->d_func()->focusPrev;
} else {
QGraphicsWidget *test = static_cast<QGraphicsWidget *>(item);
widget = next ? test->d_func()->focusNext : test->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
}
QGraphicsWidget *widgetThatHadFocus = widget;
// Run around the focus chain until we find a widget that can take tab focus.
do {
if (widget->flags() & QGraphicsItem::ItemIsFocusable
&& widget->isEnabled() && widget->isVisibleTo(0)
&& (widget->focusPolicy() & Qt::TabFocus)
&& (!item || !item->isWindow() || item->isAncestorOf(widget))
) {
setFocusItem(widget, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
return true;
}
widget = next ? widget->d_func()->focusNext : widget->d_func()->focusPrev;
if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
return false;
} while (widget != widgetThatHadFocus);
return false;
}
/*!
\fn QGraphicsScene::changed(const QList<QRectF> ®ion)
This signal is emitted by QGraphicsScene when control reaches the
event loop, if the scene content changes. The \a region parameter
contains a list of scene rectangles that indicate the area that
has been changed.
\sa QGraphicsView::updateScene()
*/
/*!
\fn QGraphicsScene::sceneRectChanged(const QRectF &rect)
This signal is emitted by QGraphicsScene whenever the scene rect changes.
The \a rect parameter is the new scene rectangle.
\sa QGraphicsView::updateSceneRect()
*/
/*!
\fn QGraphicsScene::selectionChanged()
\since 4.3
This signal is emitted by QGraphicsScene whenever the selection
changes. You can call selectedItems() to get the new list of selected
items.
The selection changes whenever an item is selected or unselected, a
selection area is set, cleared or otherwise changed, if a preselected item
is added to the scene, or if a selected item is removed from the scene.
QGraphicsScene emits this signal only once for group selection operations.
For example, if you set a selection area, select or unselect a
QGraphicsItemGroup, or if you add or remove from the scene a parent item
that contains several selected items, selectionChanged() is emitted only
once after the operation has completed (instead of once for each item).
\sa setSelectionArea(), selectedItems(), QGraphicsItem::setSelected()
*/
/*!
\internal
This private function is called by QGraphicsItem, which is a friend of
QGraphicsScene. It is used by QGraphicsScene to record the rectangles that
need updating. It also launches a single-shot timer to ensure that
updated() will be emitted later.
The \a item parameter is the item that changed, and \a rect is the
area of the item that changed given in item coordinates.
*/
void QGraphicsScene::itemUpdated(QGraphicsItem *item, const QRectF &rect)
{
Q_D(QGraphicsScene);
// Deliver the actual update.
if (!d->updateAll) {
if (d->views.isEmpty() || ((d->connectedSignals & d->changedSignalMask) && !item->d_ptr->itemIsUntransformable()
&& qFuzzyCompare(item->boundingRegionGranularity(), qreal(0.0)))) {
// This block of code is kept for compatibility. Since 4.5, by default
// QGraphicsView does not connect the signal and we use the below
// method of delivering updates.
update(item->sceneBoundingRect());
} else {
// ### Remove _q_adjustedRects().
QRectF boundingRect(adjustedItemBoundingRect(item));
if (!rect.isNull()) {
QRectF adjustedRect(rect);
_q_adjustRect(&adjustedRect);
boundingRect &= adjustedRect;
}
// Update each view directly.
for (int i = 0; i < d->views.size(); ++i)
d->views.at(i)->d_func()->itemUpdated(item, boundingRect);
}
}
if (item->d_ptr->dirty) {
d->dirtyItems << item;
d->resetDirtyItemsLater();
}
if (!item->isVisible())
return; // Hiding an item won't effect the largestUntransformableItem/sceneRect.
// Update d->largestUntransformableItem by mapping this item's bounding
// rect back to the topmost untransformable item's untransformed
// coordinate system (which sort of equals the 1:1 coordinate system of an
// untransformed view).
if (item->d_ptr->itemIsUntransformable()) {
QGraphicsItem *parent = item;
while (parent && (parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations))
parent = parent->parentItem();
d->largestUntransformableItem |= item->mapToItem(parent, item->boundingRect()).boundingRect();
}
// Only track the automatically growing scene rect if the scene has no
// defined scene rect.
if (!d->hasSceneRect) {
QRectF oldGrowingItemsBoundingRect = d->growingItemsBoundingRect;
QRectF adjustedItemSceneBoundingRect(item->sceneBoundingRect());
_q_adjustRect(&adjustedItemSceneBoundingRect);
d->growingItemsBoundingRect |= adjustedItemSceneBoundingRect;
if (d->growingItemsBoundingRect != oldGrowingItemsBoundingRect)
emit sceneRectChanged(d->growingItemsBoundingRect);
}
}
/*!
\since 4.4
Returns the scene's style, or the same as QApplication::style() if the
scene has not been explicitly assigned a style.
\sa setStyle()
*/
QStyle *QGraphicsScene::style() const
{
Q_D(const QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
return d->style ? d->style : qApp->style();
}
/*!
\since 4.4
Sets or replaces the style of the scene to \a style, and reparents the
style to this scene. Any previously assigned style is deleted. The scene's
style defaults to QApplication::style(), and serves as the default for all
QGraphicsWidget items in the scene.
Changing the style, either directly by calling this function, or
indirectly by calling QApplication::setStyle(), will automatically update
the style for all widgets in the scene that do not have a style explicitly
assigned to them.
If \a style is 0, QGraphicsScene will revert to QApplication::style().
\sa style()
*/
void QGraphicsScene::setStyle(QStyle *style)
{
Q_D(QGraphicsScene);
// ### This function, and the use of styles in general, is non-reentrant.
if (style == d->style)
return;
// Delete the old style,
delete d->style;
if ((d->style = style))
d->style->setParent(this);
// Notify the scene.
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(this, &event);
// Notify all widgets that don't have a style explicitly set.
foreach (QGraphicsItem *item, items()) {
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!widget->testAttribute(Qt::WA_SetStyle))
QApplication::sendEvent(widget, &event);
}
}
}
/*!
\property QGraphicsScene::font
\since 4.4
\brief the scene's default font
This property provides the scene's font. The scene font defaults to,
and resolves all its entries from, QApplication::font.
If the scene's font changes, either directly through setFont() or
indirectly when the application font changes, QGraphicsScene first
sends itself a \l{QEvent::FontChange}{FontChange} event, and it then
sends \l{QEvent::FontChange}{FontChange} events to all top-level
widget items in the scene. These items respond by resolving their own
fonts to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their fonts.
Changing the scene font, (directly or indirectly through
QApplication::setFont(),) automatically schedules a redraw the entire
scene.
\sa QWidget::font, QApplication::setFont(), palette, style()
*/
QFont QGraphicsScene::font() const
{
Q_D(const QGraphicsScene);
return d->font;
}
void QGraphicsScene::setFont(const QFont &font)
{
Q_D(QGraphicsScene);
QFont naturalFont = qApp->font();
naturalFont.resolve(0);
QFont resolvedFont = font.resolve(naturalFont);
d->setFont_helper(resolvedFont);
}
/*!
\property QGraphicsScene::palette
\since 4.4
\brief the scene's default palette
This property provides the scene's palette. The scene palette defaults to,
and resolves all its entries from, QApplication::palette.
If the scene's palette changes, either directly through setPalette() or
indirectly when the application palette changes, QGraphicsScene first
sends itself a \l{QEvent::PaletteChange}{PaletteChange} event, and it then
sends \l{QEvent::PaletteChange}{PaletteChange} events to all top-level
widget items in the scene. These items respond by resolving their own
palettes to the scene, and they then notify their children, who again
notify their children, and so on, until all widget items have updated
their palettes.
Changing the scene palette, (directly or indirectly through
QApplication::setPalette(),) automatically schedules a redraw the entire
scene.
\sa QWidget::palette, QApplication::setPalette(), font, style()
*/
QPalette QGraphicsScene::palette() const
{
Q_D(const QGraphicsScene);
return d->palette;
}
void QGraphicsScene::setPalette(const QPalette &palette)
{
Q_D(QGraphicsScene);
QPalette naturalPalette = qApp->palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
d->setPalette_helper(resolvedPalette);
}
/*!
\since 4.4
Returns the current active window, or 0 if there is no window is currently
active.
\sa QGraphicsScene::setActiveWindow()
*/
QGraphicsWidget *QGraphicsScene::activeWindow() const
{
Q_D(const QGraphicsScene);
return d->activeWindow;
}
/*!
\since 4.4
Activates \a widget, which must be a widget in this scene. You can also
pass 0 for \a widget, in which case QGraphicsScene will deactivate any
currently active window.
\sa activeWindow(), QGraphicsWidget::isActiveWindow()
*/
void QGraphicsScene::setActiveWindow(QGraphicsWidget *widget)
{
Q_D(QGraphicsScene);
if (widget && widget->scene() != this) {
qWarning("QGraphicsScene::setActiveWindow: widget %p must be part of this scene",
widget);
return;
}
// Activate the widget's window.
QGraphicsWidget *window = widget ? widget->window() : 0;
if (window == d->activeWindow)
return;
// Deactivate the last active window.
if (d->activeWindow) {
if (QGraphicsWidget *fw = d->activeWindow->focusWidget()) {
// Remove focus from the current focus item.
if (fw == focusItem())
setFocusItem(0, Qt::ActiveWindowFocusReason);
}
QEvent event(QEvent::WindowDeactivate);
QApplication::sendEvent(d->activeWindow, &event);
}
// Update activate state.
d->activeWindow = window;
QEvent event(QEvent::ActivationChange);
QApplication::sendEvent(this, &event);
// Activate
if (window) {
QEvent event(QEvent::WindowActivate);
QApplication::sendEvent(window, &event);
QList<QGraphicsItem *> siblingWindows;
QGraphicsItem *parent = window->parentItem();
// Raise ### inefficient for toplevels
foreach (QGraphicsItem *sibling, parent ? parent->children() : items()) {
if (sibling != window && sibling->isWidget()
&& static_cast<QGraphicsWidget *>(sibling)->isWindow()) {
siblingWindows << sibling;
}
}
// Find the highest z value.
qreal z = window->zValue();
for (int i = 0; i < siblingWindows.size(); ++i)
z = qMax(z, siblingWindows.at(i)->zValue());
// This will probably never overflow.
const qreal litt = qreal(0.001);
window->setZValue(z + litt);
if (QGraphicsWidget *focusChild = window->focusWidget())
focusChild->setFocus(Qt::ActiveWindowFocusReason);
}
}
QT_END_NAMESPACE
#include "moc_qgraphicsscene.cpp"
#endif // QT_NO_GRAPHICSVIEW
|