summaryrefslogtreecommitdiffstats
path: root/src/gui/itemviews/qabstractitemview.cpp
blob: 88879777d525be2e537c13a8750ecae4bde07ab6 (plain)
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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (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 http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qabstractitemview.h"

#ifndef QT_NO_ITEMVIEWS
#include <qpointer.h>
#include <qapplication.h>
#include <qclipboard.h>
#include <qpainter.h>
#include <qstyle.h>
#include <qdrag.h>
#include <qevent.h>
#include <qscrollbar.h>
#include <qwhatsthis.h>
#include <qtooltip.h>
#include <qdatetime.h>
#include <qlineedit.h>
#include <qspinbox.h>
#include <qstyleditemdelegate.h>
#include <private/qabstractitemview_p.h>
#include <private/qabstractitemmodel_p.h>
#ifndef QT_NO_ACCESSIBILITY
#include <qaccessible.h>
#endif

QT_BEGIN_NAMESPACE

QAbstractItemViewPrivate::QAbstractItemViewPrivate()
    :   model(QAbstractItemModelPrivate::staticEmptyModel()),
        itemDelegate(0),
        selectionModel(0),
        selectionMode(QAbstractItemView::ExtendedSelection),
        selectionBehavior(QAbstractItemView::SelectItems),
        currentlyCommittingEditor(0),
        pressedModifiers(Qt::NoModifier),
        pressedPosition(QPoint(-1, -1)),
        viewportEnteredNeeded(false),
        state(QAbstractItemView::NoState),
        editTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed),
        lastTrigger(QAbstractItemView::NoEditTriggers),
        tabKeyNavigation(false),
#ifndef QT_NO_DRAGANDDROP
        showDropIndicator(true),
        dragEnabled(false),
        dragDropMode(QAbstractItemView::NoDragDrop),
        overwrite(false),
        dropIndicatorPosition(QAbstractItemView::OnItem),
#endif
        autoScroll(true),
        autoScrollMargin(16),
        autoScrollCount(0),
        shouldScrollToCurrentOnShow(false),
        alternatingColors(false),
        textElideMode(Qt::ElideRight),
        verticalScrollMode(QAbstractItemView::ScrollPerItem),
        horizontalScrollMode(QAbstractItemView::ScrollPerItem),
        currentIndexSet(false),
        wrapItemText(false),
        delayedPendingLayout(false)
{
}

QAbstractItemViewPrivate::~QAbstractItemViewPrivate()
{
}

void QAbstractItemViewPrivate::init()
{
    Q_Q(QAbstractItemView);
    q->setItemDelegate(new QStyledItemDelegate(q));

    vbar->setRange(0, 0);
    hbar->setRange(0, 0);

    QObject::connect(vbar, SIGNAL(actionTriggered(int)),
                     q, SLOT(verticalScrollbarAction(int)));
    QObject::connect(hbar, SIGNAL(actionTriggered(int)),
                     q, SLOT(horizontalScrollbarAction(int)));
    QObject::connect(vbar, SIGNAL(valueChanged(int)),
                     q, SLOT(verticalScrollbarValueChanged(int)));
    QObject::connect(hbar, SIGNAL(valueChanged(int)),
                     q, SLOT(horizontalScrollbarValueChanged(int)));

    viewport->setBackgroundRole(QPalette::Base);

    doDelayedItemsLayout();

    q->setAttribute(Qt::WA_InputMethodEnabled);
}

void QAbstractItemViewPrivate::checkMouseMove(const QPersistentModelIndex &index)
{
    //we take a persistent model index because the model might change by emitting signals
    Q_Q(QAbstractItemView);
    if (viewportEnteredNeeded || enteredIndex != index) {
        viewportEnteredNeeded = false;

        if (index.isValid()) {
            emit q->entered(index);
#ifndef QT_NO_STATUSTIP
            QString statustip = model->data(index, Qt::StatusTipRole).toString();
            if (parent && !statustip.isEmpty()) {
                QStatusTipEvent tip(statustip);
                QApplication::sendEvent(parent, &tip);
            }
#endif
        } else {
#ifndef QT_NO_STATUSTIP
            if (parent) {
                QString emptyString;
                QStatusTipEvent tip( emptyString );
                QApplication::sendEvent(parent, &tip);
            }
#endif
            emit q->viewportEntered();
        }
        enteredIndex = index;
    }
}


/*!
    \class QAbstractItemView

    \brief The QAbstractItemView class provides the basic functionality for
    item view classes.

    \ingroup model-view
    \mainclass

    QAbstractItemView class is the base class for every standard view
    that uses a QAbstractItemModel. QAbstractItemView is an abstract
    class and cannot itself be instantiated. It provides a standard
    interface for interoperating with models through the signals and
    slots mechanism, enabling subclasses to be kept up-to-date with
    changes to their models.  This class provides standard support for
    keyboard and mouse navigation, viewport scrolling, item editing,
    and selections.

    The QAbstractItemView class is one of the \l{Model/View Classes}
    and is part of Qt's \l{Model/View Programming}{model/view framework}.

    The view classes that inherit QAbstractItemView only need
    to implement their own view-specific functionality, such as
    drawing items, returning the geometry of items, finding items,
    etc.

    QAbstractItemView provides common slots such as edit() and
    setCurrentIndex(). Many protected slots are also provided, including
    dataChanged(), rowsInserted(), rowsAboutToBeRemoved(), selectionChanged(),
    and currentChanged().

    The root item is returned by rootIndex(), and the current item by
    currentIndex(). To make sure that an item is visible use
    scrollTo().

    Some of QAbstractItemView's functions are concerned with
    scrolling, for example setHorizontalScrollMode() and
    setVerticalScrollMode(). To set the range of the scroll bars, you
    can, for example, reimplement the view's resizeEvent() function:

    \snippet doc/src/snippets/code/src_gui_itemviews_qabstractitemview.cpp 0

    Note that the range is not updated until the widget is shown.

    Several other functions are concerned with selection control; for
    example setSelectionMode(), and setSelectionBehavior(). This class
    provides a default selection model to work with
    (selectionModel()), but this can be replaced by using
    setSelectionModel() with an instance of QItemSelectionModel.

    For complete control over the display and editing of items you can
    specify a delegate with setItemDelegate().

    QAbstractItemView provides a lot of protected functions. Some are
    concerned with editing, for example, edit(), and commitData(),
    whilst others are keyboard and mouse event handlers.

    \note If you inherit QAbstractItemView and intend to update the contents
    of the viewport, you should use viewport->update() instead of
    \l{QWidget::update()}{update()} as all painting operations take place on the
    viewport.

    \sa {View Classes}, {Model/View Programming}, QAbstractItemModel, {Chart Example}
*/

/*!
    \enum QAbstractItemView::SelectionMode

    This enum indicates how the view responds to user selections:

    \value SingleSelection  When the user selects an item, any already-selected
    item becomes unselected, and the user cannot unselect the selected item by
    clicking on it.

    \value ContiguousSelection When the user selects an item in the usual way,
    the selection is cleared and the new item selected. However, if the user
    presses the Shift key while clicking on an item, all items between the
    current item and the clicked item are selected or unselected, depending on
    the state of the clicked item.

    \value ExtendedSelection When the user selects an item in the usual way,
    the selection is cleared and the new item selected. However, if the user
    presses the Ctrl key when clicking on an item, the clicked item gets
    toggled and all other items are left untouched. If the user presses the
    Shift key while clicking on an item, all items between the current item
    and the clicked item are selected or unselected, depending on the state of
    the clicked item. Multiple items can be selected by dragging the mouse over
    them.

    \value MultiSelection When the user selects an item in the usual way, the
    selection status of that item is toggled and the other items are left
    alone. Multiple items can be toggled by dragging the mouse over them.

    \value NoSelection Items cannot be selected.

    The most commonly used modes are SingleSelection and ExtendedSelection.
*/

/*!
    \enum QAbstractItemView::SelectionBehavior

    \value SelectItems   Selecting single items.
    \value SelectRows    Selecting only rows.
    \value SelectColumns Selecting only columns.
*/

/*!
    \enum QAbstractItemView::ScrollHint

    \value EnsureVisible  Scroll to ensure that the item is visible.
    \value PositionAtTop  Scroll to position the item at the top of the
           viewport.
    \value PositionAtBottom  Scroll to position the item at the bottom of the
           viewport.
    \value PositionAtCenter  Scroll to position the item at the center of the
           viewport.
*/


/*!
    \enum QAbstractItemView::EditTrigger

    This enum describes actions which will initiate item editing.

    \value NoEditTriggers  No editing possible.
    \value CurrentChanged  Editing start whenever current item changes.
    \value DoubleClicked   Editing starts when an item is double clicked.
    \value SelectedClicked Editing starts when clicking on an already selected
           item.
    \value EditKeyPressed  Editing starts when the platform edit key has been
           pressed over an item.
    \value AnyKeyPressed   Editing starts when any key is pressed over an item.
    \value AllEditTriggers Editing starts for all above actions.
*/

/*!
    \enum QAbstractItemView::CursorAction

    This enum describes the different ways to navigate between items,
    \sa moveCursor()

    \value MoveUp       Move to the item above the current item.
    \value MoveDown     Move to the item below the current item.
    \value MoveLeft     Move to the item left of the current item.
    \value MoveRight    Move to the item right of the current item.
    \value MoveHome     Move to the top-left corner item.
    \value MoveEnd      Move to the bottom-right corner item.
    \value MovePageUp   Move one page up above the current item.
    \value MovePageDown Move one page down below the current item.
    \value MoveNext     Move to the item after the current item.
    \value MovePrevious Move to the item before the current item.
*/

/*!
    \enum QAbstractItemView::State

    Describes the different states the view can be in. This is usually
    only interesting when reimplementing your own view.

    \value NoState        The is the default state.
    \value DraggingState  The user is dragging items.
    \value DragSelectingState The user is selecting items.
    \value EditingState   The user is editing an item in a widget editor.
    \value ExpandingState   The user is opening a branch of items.
    \value CollapsingState   The user is closing a branch of items.
    \value AnimatingState The item view is performing an animation.
*/

/*!
    \since 4.2
    \enum QAbstractItemView::ScrollMode

    \value ScrollPerItem    The view will scroll the contents one item at a time.
    \value ScrollPerPixel   The view will scroll the contents one pixel at a time.
*/

/*!
    \fn QRect QAbstractItemView::visualRect(const QModelIndex &index) const = 0
    Returns the rectangle on the viewport occupied by the item at \a index.

    If your item is displayed in several areas then visualRect should return
    the primary area that contains index and not the complete area that index
    might encompasses, touch or cause drawing.

    In the base class this is a pure virtual function.

    \sa indexAt(), visualRegionForSelection()
*/

/*!
    \fn void QAbstractItemView::scrollTo(const QModelIndex &index, ScrollHint hint) = 0

    Scrolls the view if necessary to ensure that the item at \a index
    is visible. The view will try to position the item according to the given \a hint.

    In the base class this is a pure virtual function.
*/

/*!
    \fn QModelIndex QAbstractItemView::indexAt(const QPoint &point) const = 0

    Returns the model index of the item at the viewport coordinates \a point.

    In the base class this is a pure virtual function.

    \sa visualRect()
*/

/*!
    \fn void QAbstractItemView::activated(const QModelIndex &index)

    This signal is emitted when the item specified by \a index is
    activated by the user. How to activate items depends on the
    platform; e.g., by single- or double-clicking the item, or by
    pressing the Return or Enter key when the item is current.

    \sa clicked(), doubleClicked(), entered(), pressed()
*/

/*!
    \fn void QAbstractItemView::entered(const QModelIndex &index)

    This signal is emitted when the mouse cursor enters the item
    specified by \a index.
    Mouse tracking needs to be enabled for this feature to work.

    \sa viewportEntered(), activated(), clicked(), doubleClicked(), pressed()
*/

/*!
    \fn void QAbstractItemView::viewportEntered()

    This signal is emitted when the mouse cursor enters the viewport.
    Mouse tracking needs to be enabled for this feature to work.

    \sa entered()
*/

/*!
    \fn void QAbstractItemView::pressed(const QModelIndex &index)

    This signal is emitted when a mouse button is pressed. The item
    the mouse was pressed on is specified by \a index. The signal is
    only emitted when the index is valid.

    Use the QApplication::mouseButtons() function to get the state
    of the mouse buttons.

    \sa activated(), clicked(), doubleClicked(), entered()
*/

/*!
    \fn void QAbstractItemView::clicked(const QModelIndex &index)

    This signal is emitted when a mouse button is clicked. The item
    the mouse was clicked on is specified by \a index. The signal is
    only emitted when the index is valid.

    \sa activated(), doubleClicked(), entered(), pressed()
*/

/*!
    \fn void QAbstractItemView::doubleClicked(const QModelIndex &index)

    This signal is emitted when a mouse button is double-clicked. The
    item the mouse was double-clicked on is specified by \a index.
    The signal is only emitted when the index is valid.

    \sa clicked(), activated()
*/

/*!
    \fn QModelIndex QAbstractItemView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) = 0

    Returns a QModelIndex object pointing to the next object in the view,
    based on the given \a cursorAction and keyboard modifiers specified
    by \a modifiers.

    In the base class this is a pure virtual function.
*/

/*!
    \fn int QAbstractItemView::horizontalOffset() const = 0

    Returns the horizontal offset of the view.

    In the base class this is a pure virtual function.

    \sa verticalOffset()
*/

/*!
    \fn int QAbstractItemView::verticalOffset() const = 0

    Returns the vertical offset of the view.

    In the base class this is a pure virtual function.

    \sa horizontalOffset()
*/

/*!
    \fn bool QAbstractItemView::isIndexHidden(const QModelIndex &index) const

    Returns true if the item referred to by the given \a index is hidden in the view,
    otherwise returns false.

    Hiding is a view specific feature.  For example in TableView a column can be marked
    as hidden or a row in the TreeView.

    In the base class this is a pure virtual function.
*/

/*!
    \fn void QAbstractItemView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags flags)

    Applies the selection \a flags to the items in or touched by the
    rectangle, \a rect.

    When implementing your own itemview setSelection should call
    selectionModel()->select(selection, flags) where selection
    is either an empty QModelIndex or a QItemSelection that contains
    all items that are contained in \a rect.

    \sa selectionCommand(), selectedIndexes()
*/

/*!
    \fn QRegion QAbstractItemView::visualRegionForSelection(const QItemSelection &selection) const = 0

    Returns the region from the viewport of the items in the given
    \a selection.

    In the base class this is a pure virtual function.

    \sa visualRect(), selectedIndexes()
*/

/*!
    \fn void QAbstractItemView::update()
    \internal
*/

/*!
    Constructs an abstract item view with the given \a parent.
*/
QAbstractItemView::QAbstractItemView(QWidget *parent)
    : QAbstractScrollArea(*(new QAbstractItemViewPrivate), parent)
{
    d_func()->init();
}

/*!
    \internal
*/
QAbstractItemView::QAbstractItemView(QAbstractItemViewPrivate &dd, QWidget *parent)
    : QAbstractScrollArea(dd, parent)
{
    d_func()->init();
}

/*!
    Destroys the view.
*/
QAbstractItemView::~QAbstractItemView()
{
}

/*!
    Sets the \a model for the view to present.

    This function will create and set a new selection model, replacing any
    model that was previously set with setSelectionModel(). However, the old
    selection model will not be deleted as it may be shared between several
    views. We recommend that you delete the old selection model if it is no
    longer required. This is done with the following code:

    \snippet doc/src/snippets/code/src_gui_itemviews_qabstractitemview.cpp 2

    If both the old model and the old selection model do not have parents, or
    if their parents are long-lived objects, it may be preferable to call their
    deleteLater() functions to explicitly delete them.

    The view \e{does not} take ownership of the model unless it is the model's
    parent object because the view may be shared between many different views.

  \sa selectionModel(), setSelectionModel()
*/
void QAbstractItemView::setModel(QAbstractItemModel *model)
{
    Q_D(QAbstractItemView);
    if (model == d->model)
        return;
    if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
        disconnect(d->model, SIGNAL(destroyed()),
                   this, SLOT(_q_modelDestroyed()));
        disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
                   this, SLOT(dataChanged(QModelIndex,QModelIndex)));
        disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
                   this, SLOT(rowsInserted(QModelIndex,int,int)));
        disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
                   this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int)));
        disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
                   this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
        disconnect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
                   this, SLOT(_q_columnsAboutToBeRemoved(QModelIndex,int,int)));
        disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
                   this, SLOT(_q_columnsRemoved(QModelIndex,int,int)));
        disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
                   this, SLOT(_q_columnsInserted(QModelIndex,int,int)));

        disconnect(d->model, SIGNAL(modelReset()), this, SLOT(reset()));
        disconnect(d->model, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged()));
    }
    d->model = (model ? model : QAbstractItemModelPrivate::staticEmptyModel());

    // These asserts do basic sanity checking of the model
    Q_ASSERT_X(d->model->index(0,0) == d->model->index(0,0),
               "QAbstractItemView::setModel",
               "A model should return the exact same index "
               "(including its internal id/pointer) when asked for it twice in a row.");
    Q_ASSERT_X(d->model->index(0,0).parent() == QModelIndex(),
               "QAbstractItemView::setModel",
               "The parent of a top level index should be invalid");

    if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
        connect(d->model, SIGNAL(destroyed()),
                this, SLOT(_q_modelDestroyed()));
        connect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
                this, SLOT(dataChanged(QModelIndex,QModelIndex)));
        connect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
                this, SLOT(rowsInserted(QModelIndex,int,int)));
        connect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
                this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int)));
        connect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
                this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
        connect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
                this, SLOT(_q_columnsAboutToBeRemoved(QModelIndex,int,int)));
        connect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
                this, SLOT(_q_columnsRemoved(QModelIndex,int,int)));
        connect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
                this, SLOT(_q_columnsInserted(QModelIndex,int,int)));

        connect(d->model, SIGNAL(modelReset()), this, SLOT(reset()));
        connect(d->model, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged()));
    }
    setSelectionModel(new QItemSelectionModel(d->model, this));
    reset(); // kill editors, set new root and do layout
}

/*!
    Returns the model that this view is presenting.
*/
QAbstractItemModel *QAbstractItemView::model() const
{
    Q_D(const QAbstractItemView);
    return (d->model == QAbstractItemModelPrivate::staticEmptyModel() ? 0 : d->model);
}

/*!
    Sets the current selection model to the given \a selectionModel.

    Note that, if you call setModel() after this function, the given \a selectionModel
    will be replaced by one created by the view.

    \note It is up to the application to delete the old selection model if it is no
    longer needed; i.e., if it is not being used by other views. This will happen
    automatically when its parent object is deleted. However, if it does not have a
    parent, or if the parent is a long-lived object, it may be preferable to call its
    deleteLater() function to explicitly delete it.

    \sa selectionModel(), setModel(), clearSelection()
*/
void QAbstractItemView::setSelectionModel(QItemSelectionModel *selectionModel)
{
    // ### if the given model is null, we should use the original selection model
    Q_ASSERT(selectionModel);
    Q_D(QAbstractItemView);

    if (selectionModel->model() != d->model) {
        qWarning("QAbstractItemView::setSelectionModel() failed: "
                 "Trying to set a selection model, which works on "
                 "a different model than the view.");
        return;
    }

    if (d->selectionModel) {
        disconnect(d->selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
                   this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
        disconnect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
                   this, SLOT(currentChanged(QModelIndex,QModelIndex)));
    }

    d->selectionModel = selectionModel;

    if (d->selectionModel) {
        connect(d->selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
                this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
        connect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
                this, SLOT(currentChanged(QModelIndex,QModelIndex)));
    }
}

/*!
    Returns the current selection model.

    \sa setSelectionModel(), selectedIndexes()
*/
QItemSelectionModel* QAbstractItemView::selectionModel() const
{
    Q_D(const QAbstractItemView);
    return d->selectionModel;
}

/*!
    Sets the item delegate for this view and its model to \a delegate.
    This is useful if you want complete control over the editing and
    display of items.

    Any existing delegate will be removed, but not deleted. QAbstractItemView
    does not take ownership of \a delegate.

    \warning You should not share the same instance of a delegate between views.
    Doing so can cause incorrect or unintuitive editing behavior since each
    view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
    signal, and attempt to access, modify or close an editor that has already been closed.

    \sa itemDelegate()
*/
void QAbstractItemView::setItemDelegate(QAbstractItemDelegate *delegate)
{
    Q_D(QAbstractItemView);
    if (delegate == d->itemDelegate)
        return;

    if (d->itemDelegate) {
        if (d->delegateRefCount(d->itemDelegate) == 1) {
            disconnect(d->itemDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
                       this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
            disconnect(d->itemDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
            disconnect(d->itemDelegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(doItemsLayout()));
        }
    }


    if (delegate) {
        if (d->delegateRefCount(delegate) == 0) {
            connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
                    this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
            connect(delegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
            qRegisterMetaType<QModelIndex>("QModelIndex");
            connect(delegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(doItemsLayout()), Qt::QueuedConnection);
        }
    }
    d->itemDelegate = delegate;
}

/*!
    Returns the item delegate used by this view and model. This is
    either one set with setItemDelegate(), or the default one.

    \sa setItemDelegate()
*/
QAbstractItemDelegate *QAbstractItemView::itemDelegate() const
{
    return d_func()->itemDelegate;
}

/*!
    \reimp
*/
QVariant QAbstractItemView::inputMethodQuery(Qt::InputMethodQuery query) const
{
    const QModelIndex current = currentIndex();
    if (!current.isValid() || query != Qt::ImMicroFocus)
        return QAbstractScrollArea::inputMethodQuery(query);
    return visualRect(current);
}

/*!
    \since 4.2

    Sets the given item \a delegate used by this view and model for the given
    \a row. All items on \a row will be drawn and managed by \a delegate
    instead of using the default delegate (i.e., itemDelegate()).

    Any existing row delegate for \a row will be removed, but not
    deleted. QAbstractItemView does not take ownership of \a delegate.

    \note If a delegate has been assigned to both a row and a column, the row
    delegate (i.e., this delegate) will take presedence and manage the
    intersecting cell index.

    \warning You should not share the same instance of a delegate between views.
    Doing so can cause incorrect or unintuitive editing behavior since each
    view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
    signal, and attempt to access, modify or close an editor that has already been closed.

    \sa itemDelegateForRow(), setItemDelegateForColumn(), itemDelegate()
*/
void QAbstractItemView::setItemDelegateForRow(int row, QAbstractItemDelegate *delegate)
{
    Q_D(QAbstractItemView);
    if (QAbstractItemDelegate *rowDelegate = d->rowDelegates.value(row, 0)) {
        if (d->delegateRefCount(rowDelegate) == 1) {
            disconnect(rowDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
                       this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
            disconnect(rowDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
        }
        d->rowDelegates.remove(row);
    }
    if (delegate) {
        if (d->delegateRefCount(delegate) == 0) {
            connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
                    this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
            connect(delegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
        }
        d->rowDelegates.insert(row, delegate);
    }
}

/*!
   \since 4.2

   Returns the item delegate used by this view and model for the given \a row,
   or 0 if no delegate has been assigned. You can call itemDelegate() to get a
   pointer to the current delegate for a given index.

   \sa setItemDelegateForRow(), itemDelegateForColumn(), setItemDelegate()
*/
QAbstractItemDelegate *QAbstractItemView::itemDelegateForRow(int row) const
{
    Q_D(const QAbstractItemView);
    return d->rowDelegates.value(row, 0);
}

/*!
    \since 4.2

    Sets the given item \a delegate used by this view and model for the given
    \a column. All items on \a column will be drawn and managed by \a delegate
    instead of using the default delegate (i.e., itemDelegate()).

    Any existing column delegate for \a column will be removed, but not
    deleted. QAbstractItemView does not take ownership of \a delegate.

    \note If a delegate has been assigned to both a row and a column, the row
    delegate will take presedence and manage the intersecting cell index.

    \warning You should not share the same instance of a delegate between views.
    Doing so can cause incorrect or unintuitive editing behavior since each
    view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
    signal, and attempt to access, modify or close an editor that has already been closed.

    \sa itemDelegateForColumn(), setItemDelegateForRow(), itemDelegate()
*/
void QAbstractItemView::setItemDelegateForColumn(int column, QAbstractItemDelegate *delegate)
{
    Q_D(QAbstractItemView);
    if (QAbstractItemDelegate *columnDelegate = d->columnDelegates.value(column, 0)) {
        if (d->delegateRefCount(columnDelegate) == 1) {
            disconnect(columnDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
                       this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
            disconnect(columnDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
        }
        d->columnDelegates.remove(column);
    }
    if (delegate) {
        if (d->delegateRefCount(delegate) == 0) {
            connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
                    this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
            connect(delegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
        }
        d->columnDelegates.insert(column, delegate);
    }
}

/*!
    \since 4.2

    Returns the item delegate used by this view and model for the given \a
    column.  You can call itemDelegate() to get a pointer to the current delegate
    for a given index.

    \sa setItemDelegateForColumn(), itemDelegateForRow(), itemDelegate()
*/
QAbstractItemDelegate *QAbstractItemView::itemDelegateForColumn(int column) const
{
    Q_D(const QAbstractItemView);
    return d->columnDelegates.value(column, 0);
}

/*!
   Returns the item delegate used by this view and model for
   the given \a index.
*/
QAbstractItemDelegate *QAbstractItemView::itemDelegate(const QModelIndex &index) const
{
    Q_D(const QAbstractItemView);
    return d->delegateForIndex(index);
}

/*!
  \property QAbstractItemView::selectionMode
  \brief which selection mode the view operates in

  This property controls whether the user can select one or many items
  and, in many-item selections, whether the selection must be a
  continuous range of items.

  \sa SelectionMode SelectionBehavior
*/
void QAbstractItemView::setSelectionMode(SelectionMode mode)
{
    Q_D(QAbstractItemView);
    d->selectionMode = mode;
}

QAbstractItemView::SelectionMode QAbstractItemView::selectionMode() const
{
    Q_D(const QAbstractItemView);
    return d->selectionMode;
}

/*!
  \property QAbstractItemView::selectionBehavior
  \brief which selection behavior the view uses

  This property holds whether selections are done
  in terms of single items, rows or columns.

  \sa SelectionMode SelectionBehavior
*/

void QAbstractItemView::setSelectionBehavior(QAbstractItemView::SelectionBehavior behavior)
{
    Q_D(QAbstractItemView);
    d->selectionBehavior = behavior;
}

QAbstractItemView::SelectionBehavior QAbstractItemView::selectionBehavior() const
{
    Q_D(const QAbstractItemView);
    return d->selectionBehavior;
}

/*!
    Sets the current item to be the item at \a index.
    Depending on the current selection mode, the item may also be selected.
    Note that this function also updates the starting position for any
    new selections the user performs.

    To set an item as the current item without selecting it, call

    \c{selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);}

    \sa currentIndex(), currentChanged(), selectionMode
*/
void QAbstractItemView::setCurrentIndex(const QModelIndex &index)
{
    Q_D(QAbstractItemView);
    if (d->selectionModel && (!index.isValid() || d->isIndexEnabled(index))) {
        QItemSelectionModel::SelectionFlags command = selectionCommand(index, 0);
        d->selectionModel->setCurrentIndex(index, command);
        d->currentIndexSet = true;
        if ((command & QItemSelectionModel::Current) == 0)
            d->pressedPosition = visualRect(currentIndex()).center() + d->offset();
    }
}

/*!
    Returns the model index of the current item.

    \sa setCurrentIndex()
*/
QModelIndex QAbstractItemView::currentIndex() const
{
    Q_D(const QAbstractItemView);
    return d->selectionModel ? d->selectionModel->currentIndex() : QModelIndex();
}


/*!
    Reset the internal state of the view.

    \warning This function will reset open editors, scroll bar positions,
    selections, etc. Existing changes will not be committed. If you would like
    to save your changes when resetting the view, you can reimplement this
    function, commit your changes, and then call the superclass'
    implementation.
*/
void QAbstractItemView::reset()
{
    Q_D(QAbstractItemView);
    QList<QEditorInfo>::const_iterator it = d->editors.constBegin();
    for (; it != d->editors.constEnd(); ++it)
        d->releaseEditor(it->editor);
    d->editors.clear();
    d->persistent.clear();
    d->currentIndexSet = false;
    setState(NoState);
    setRootIndex(QModelIndex());
}

/*!
    Sets the root item to the item at the given \a index.

    \sa rootIndex()
*/
void QAbstractItemView::setRootIndex(const QModelIndex &index)
{
    Q_D(QAbstractItemView);
    if (index.isValid() && index.model() != d->model) {
        qWarning("QAbstractItemView::setRootIndex failed : index must be from the currently set model");
        return;
    }
    d->root = index;
    d->doDelayedItemsLayout();
}

/*!
    Returns the model index of the model's root item. The root item is
    the parent item to the view's toplevel items. The root can be invalid.

    \sa setRootIndex()
*/
QModelIndex QAbstractItemView::rootIndex() const
{
    return QModelIndex(d_func()->root);
}

/*!
  Selects all item in the view.
  This function wil use the selection selection behavior
  set on the view when selecting.

  \sa setSelection(), selectedIndexes(), clearSelection()
*/
void QAbstractItemView::selectAll()
{
    Q_D(QAbstractItemView);
    SelectionMode mode = d->selectionMode;
    if (mode == MultiSelection || mode == ExtendedSelection)
        d->selectAll(QItemSelectionModel::ClearAndSelect
                     |d->selectionBehaviorFlags());
    else if (mode != SingleSelection)
        d->selectAll(selectionCommand(d->model->index(0, 0, d->root)));
}

/*!
    Starts editing the item corresponding to the given \a index if it is
    editable.

    Note that this function does not change the current index. Since the current
    index defines the next and previous items to edit, users may find that
    keyboard navigation does not work as expected. To provide consistent navigation
    behavior, call setCurrentIndex() before this function with the same model
    index.

    \sa QModelIndex::flags()
*/
void QAbstractItemView::edit(const QModelIndex &index)
{
    Q_D(QAbstractItemView);
    if (!d->isIndexValid(index))
        qWarning("edit: index was invalid");
    if (!edit(index, AllEditTriggers, 0))
        qWarning("edit: editing failed");
}

/*!
    Deselects all selected items. The current index will not be changed.

    \sa setSelection(), selectAll()
*/
void QAbstractItemView::clearSelection()
{
    Q_D(QAbstractItemView);
    if (d->selectionModel)
        d->selectionModel->clearSelection();
}

/*!
    \internal

    This function is intended to lay out the items in the view.
    The default implementation just calls updateGeometries() and updates the viewport.
*/
void QAbstractItemView::doItemsLayout()
{
    Q_D(QAbstractItemView);
    d->interruptDelayedItemsLayout();
    updateGeometries();
    d->viewport->update();
}

/*!
    \property QAbstractItemView::editTriggers
    \brief which actions will initiate item editing

    This property is a selection of flags defined by
    \l{EditTrigger}, combined using the OR
    operator. The view will only initiate the editing of an item if the
    action performed is set in this property.
*/
void QAbstractItemView::setEditTriggers(EditTriggers actions)
{
    Q_D(QAbstractItemView);
    d->editTriggers = actions;
}

QAbstractItemView::EditTriggers QAbstractItemView::editTriggers() const
{
    Q_D(const QAbstractItemView);
    return d->editTriggers;
}

/*!
    \since 4.2
    \property QAbstractItemView::verticalScrollMode
    \brief how the view scrolls its contents in the vertical direction

    This property controlls how the view scroll its contents vertically.
    Scrolling can be done either per pixel or per item.
*/

void QAbstractItemView::setVerticalScrollMode(ScrollMode mode)
{
    Q_D(QAbstractItemView);
    if (mode == d->verticalScrollMode)
        return;
    QModelIndex topLeft = indexAt(QPoint(0, 0));
    d->verticalScrollMode = mode;
    updateGeometries(); // update the scroll bars
    scrollTo(topLeft, QAbstractItemView::PositionAtTop);
}

QAbstractItemView::ScrollMode QAbstractItemView::verticalScrollMode() const
{
    Q_D(const QAbstractItemView);
    return d->verticalScrollMode;
}

/*!
    \since 4.2
    \property QAbstractItemView::horizontalScrollMode
    \brief how the view scrolls its contents in the horizontal direction

    This property controlls how the view scroll its contents horizontally.
    Scrolling can be done either per pixel or per item.
*/

void QAbstractItemView::setHorizontalScrollMode(ScrollMode mode)
{
    Q_D(QAbstractItemView);
    d->horizontalScrollMode = mode;
    updateGeometries(); // update the scroll bars
}

QAbstractItemView::ScrollMode QAbstractItemView::horizontalScrollMode() const
{
    Q_D(const QAbstractItemView);
    return d->horizontalScrollMode;
}

#ifndef QT_NO_DRAGANDDROP
/*!
    \since 4.2
    \property QAbstractItemView::dragDropOverwriteMode
    \brief the view's drag and drop behavior

    If its value is \c true, the selected data will overwrite the
    existing item data when dropped, while moving the data will clear
    the item. If its value is \c false, the selected data will be
    inserted as a new item when the data is dropped. When the data is
    moved, the item is removed as well.

    The default value is \c false, as in the QListView and QTreeView
    subclasses. In the QTableView subclass, on the other hand, the
    property has been set to \c true.

    Note: This is not intended to prevent overwriting of items.
    The model's implementation of flags() should do that by not
    returning Qt::ItemIsDropEnabled.

    \sa dragDropMode
*/
void QAbstractItemView::setDragDropOverwriteMode(bool overwrite)
{
    Q_D(QAbstractItemView);
    d->overwrite = overwrite;
}

bool QAbstractItemView::dragDropOverwriteMode() const
{
    Q_D(const QAbstractItemView);
    return d->overwrite;
}
#endif

/*!
    \property QAbstractItemView::autoScroll
    \brief whether autoscrolling in drag move events is enabled

    If this property is set to true (the default), the
    QAbstractItemView automatically scrolls the contents of the view
    if the user drags within 16 pixels of the viewport edge. If the current
    item changes, then the view will scroll automatically to ensure that the
    current item is fully visible.

    This property only works if the viewport accepts drops. Autoscroll is
    switched off by setting this property to false.
*/

void QAbstractItemView::setAutoScroll(bool enable)
{
    Q_D(QAbstractItemView);
    d->autoScroll = enable;
}

bool QAbstractItemView::hasAutoScroll() const
{
    Q_D(const QAbstractItemView);
    return d->autoScroll;
}

/*!
    \since 4.4
    \property QAbstractItemView::autoScrollMargin
    \brief the size of the area when auto scrolling is triggered

    This property controlls the size of the area at the edge of the viewport that
    triggers autoscrolling. The default value is 16 pixels.
*/
void QAbstractItemView::setAutoScrollMargin(int margin)
{
    Q_D(QAbstractItemView);
    d->autoScrollMargin = margin;
}

int QAbstractItemView::autoScrollMargin() const
{
    Q_D(const QAbstractItemView);
    return d->autoScrollMargin;
}

/*!
  \property QAbstractItemView::tabKeyNavigation
  \brief whether item navigation with tab and backtab is enabled.
*/

void QAbstractItemView::setTabKeyNavigation(bool enable)
{
    Q_D(QAbstractItemView);
    d->tabKeyNavigation = enable;
}

bool QAbstractItemView::tabKeyNavigation() const
{
    Q_D(const QAbstractItemView);
    return d->tabKeyNavigation;
}

#ifndef QT_NO_DRAGANDDROP
/*!
  \property QAbstractItemView::showDropIndicator
  \brief whether the drop indicator is shown when dragging items and dropping.

  \sa dragEnabled DragDropMode dragDropOverwriteMode acceptDrops
*/

void QAbstractItemView::setDropIndicatorShown(bool enable)
{
    Q_D(QAbstractItemView);
    d->showDropIndicator = enable;
}

bool QAbstractItemView::showDropIndicator() const
{
    Q_D(const QAbstractItemView);
    return d->showDropIndicator;
}

/*!
  \property QAbstractItemView::dragEnabled
  \brief whether the view supports dragging of its own items

  \sa showDropIndicator DragDropMode dragDropOverwriteMode acceptDrops
*/

void QAbstractItemView::setDragEnabled(bool enable)
{
    Q_D(QAbstractItemView);
    d->dragEnabled = enable;
}

bool QAbstractItemView::dragEnabled() const
{
    Q_D(const QAbstractItemView);
    return d->dragEnabled;
}

/*!
    \since 4.2
    \enum QAbstractItemView::DragDropMode

    Describes the various drag and drop events the view can act upon.
    By default the view does not support dragging or dropping (\c
    NoDragDrop).

    \value NoDragDrop Does not support dragging or dropping.
    \value DragOnly The view supports dragging of its own items
    \value DropOnly The view accepts drops
    \value DragDrop The view supports both dragging and dropping
    \value InternalMove The view accepts move (\bold{not copy}) operations only
           from itself.

    Note that the model used needs to provide support for drag and drop operations.

    \sa setDragDropMode() {Using Drag and Drop with Item Views}
*/

/*!
  \property QAbstractItemView::dragDropMode
  \brief the drag and drop event the view will act upon

  \since 4.2
  \sa showDropIndicator dragDropOverwriteMode
*/
void QAbstractItemView::setDragDropMode(DragDropMode behavior)
{
    Q_D(QAbstractItemView);
    d->dragDropMode = behavior;
    setDragEnabled(behavior == DragOnly || behavior == DragDrop || behavior == InternalMove);
    setAcceptDrops(behavior == DropOnly || behavior == DragDrop || behavior == InternalMove);
}

QAbstractItemView::DragDropMode QAbstractItemView::dragDropMode() const
{
    Q_D(const QAbstractItemView);
    DragDropMode setBehavior = d->dragDropMode;
    if (!dragEnabled() && !acceptDrops())
        return NoDragDrop;

    if (dragEnabled() && !acceptDrops())
        return DragOnly;

    if (!dragEnabled() && acceptDrops())
        return DropOnly;

    if (dragEnabled() && acceptDrops()) {
        if (setBehavior == InternalMove)
            return setBehavior;
        else
            return DragDrop;
    }

    return NoDragDrop;
}

#endif // QT_NO_DRAGANDDROP

/*!
  \property QAbstractItemView::alternatingRowColors
  \brief whether to draw the background using alternating colors

  If this property is true, the item background will be drawn using
  QPalette::Base and QPalette::AlternateBase; otherwise the background
  will be drawn using the QPalette::Base color.

  By default, this property is false.
*/
void QAbstractItemView::setAlternatingRowColors(bool enable)
{
    Q_D(QAbstractItemView);
    d->alternatingColors = enable;
    if (isVisible())
        d->viewport->update();
}

bool QAbstractItemView::alternatingRowColors() const
{
    Q_D(const QAbstractItemView);
    return d->alternatingColors;
}

/*!
    \property QAbstractItemView::iconSize
    \brief the size of items' icons

    Setting this property when the view is visible will cause the
    items to be laid out again.
*/
void QAbstractItemView::setIconSize(const QSize &size)
{
    Q_D(QAbstractItemView);
    if (size == d->iconSize)
        return;
    d->iconSize = size;
    d->doDelayedItemsLayout();
}

QSize QAbstractItemView::iconSize() const
{
    Q_D(const QAbstractItemView);
    return d->iconSize;
}

/*!
    \property QAbstractItemView::textElideMode

    \brief the position of the "..." in elided text.

    The default value for all item views is Qt::ElideRight.
*/
void QAbstractItemView::setTextElideMode(Qt::TextElideMode mode)
{
    Q_D(QAbstractItemView);
    d->textElideMode = mode;
}

Qt::TextElideMode QAbstractItemView::textElideMode() const
{
    return d_func()->textElideMode;
}

/*!
  \reimp
*/
bool QAbstractItemView::focusNextPrevChild(bool next)
{
    Q_D(QAbstractItemView);
    if (d->tabKeyNavigation && isEnabled() && d->viewport->isEnabled()) {
        QKeyEvent event(QEvent::KeyPress, next ? Qt::Key_Tab : Qt::Key_Backtab, Qt::NoModifier);
        keyPressEvent(&event);
        if (event.isAccepted())
            return true;
    }
    return QAbstractScrollArea::focusNextPrevChild(next);
}

/*!
  \reimp
*/
bool QAbstractItemView::event(QEvent *event)
{
    Q_D(QAbstractItemView);
    switch (event->type()) {
    case QEvent::Paint:
        //we call this here because the scrollbars' visibility might be altered
        //so this can't be done in the paintEvent method
        d->executePostedLayout(); //make sure we set the layout properly
        break;
    case QEvent::Show:
        d->executePostedLayout(); //make sure we set the layout properly
        if (d->shouldScrollToCurrentOnShow) {
            d->shouldScrollToCurrentOnShow = false;
            const QModelIndex current = currentIndex();
            if (current.isValid() && (d->state == QAbstractItemView::EditingState || d->autoScroll))
                scrollTo(current);
        }
        break;
    case QEvent::LocaleChange:
        viewport()->update();
        break;
    case QEvent::LayoutDirectionChange:
    case QEvent::ApplicationLayoutDirectionChange:
        updateGeometries();
        break;
    case QEvent::StyleChange:
        doItemsLayout();
        break;
    case QEvent::FocusOut:
        d->checkPersistentEditorFocus();
        break;
    case QEvent::FontChange:
        d->doDelayedItemsLayout(); // the size of the items will change
        break;
    default:
        break;
    }
    return QAbstractScrollArea::event(event);
}

/*!
    \fn bool QAbstractItemView::viewportEvent(QEvent *event)

    This function is used to handle tool tips, and What's
    This? mode, if the given \a event is a QEvent::ToolTip,or a
    QEvent::WhatsThis. It passes all other
    events on to its base class viewportEvent() handler.
*/
bool QAbstractItemView::viewportEvent(QEvent *event)
{
    Q_D(QAbstractItemView);
    switch (event->type()) {
    case QEvent::HoverEnter: {
        QHoverEvent *he = static_cast<QHoverEvent*>(event);
        d->hover = indexAt(he->pos());
        update(d->hover);
        break; }
    case QEvent::HoverLeave: {
        update(d->hover); // update old
        d->hover = QModelIndex();
        break; }
    case QEvent::HoverMove: {
        QHoverEvent *he = static_cast<QHoverEvent*>(event);
        QModelIndex old = d->hover;
        d->hover = indexAt(he->pos());
        if (d->hover != old)
            d->viewport->update(visualRect(old)|visualRect(d->hover));
        break; }
    case QEvent::Enter:
        d->viewportEnteredNeeded = true;
        break;
    case QEvent::Leave:
        d->enteredIndex = QModelIndex();
        break;
    case QEvent::ToolTip:
    case QEvent::QueryWhatsThis:
    case QEvent::WhatsThis: {
        QHelpEvent *he = static_cast<QHelpEvent*>(event);
        const QModelIndex index = indexAt(he->pos());
        QStyleOptionViewItemV4 option = d->viewOptionsV4();
        option.rect = visualRect(index);
        option.state |= (index == currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
        bool retval = false;
        // ### Qt 5: make this a normal function call to a virtual function
        QMetaObject::invokeMethod(d->delegateForIndex(index), "helpEvent",
                                  Q_RETURN_ARG(bool, retval),
                                  Q_ARG(QHelpEvent *, he),
                                  Q_ARG(QAbstractItemView *, this),
                                  Q_ARG(QStyleOptionViewItem, option),
                                  Q_ARG(QModelIndex, index));
        return retval;
    }
    case QEvent::FontChange:
        d->doDelayedItemsLayout(); // the size of the items will change
        break;
    case QEvent::WindowActivate:
    case QEvent::WindowDeactivate:
        d->viewport->update();
        break;
    default:
        break;
    }
    return QAbstractScrollArea::viewportEvent(event);
}

/*!
    This function is called with the given \a event when a mouse button is pressed
    while the cursor is inside the widget. If a valid item is pressed on it is made
    into the current item. This function emits the pressed() signal.
*/
void QAbstractItemView::mousePressEvent(QMouseEvent *event)
{
    Q_D(QAbstractItemView);
    d->delayedAutoScroll.stop(); //any interaction with the view cancel the auto scrolling
    QPoint pos = event->pos();
    QPersistentModelIndex index = indexAt(pos);

    if (!d->selectionModel
        || (d->state == EditingState && d->hasEditor(index)))
        return;

    d->pressedAlreadySelected = d->selectionModel->isSelected(index);
    d->pressedIndex = index;
    d->pressedModifiers = event->modifiers();
    QItemSelectionModel::SelectionFlags command = selectionCommand(index, event);
    QPoint offset = d->offset();
    if ((command & QItemSelectionModel::Current) == 0)
        d->pressedPosition = pos + offset;

    if (d->pressedPosition == QPoint(-1, -1))
        d->pressedPosition = visualRect(currentIndex()).center() + offset;

    if (edit(index, NoEditTriggers, event))
        return;

    if (index.isValid() && d->isIndexEnabled(index)) {
        // we disable scrollTo for mouse press so the item doesn't change position
        // when the user is interacting with it (ie. clicking on it)
        bool autoScroll = d->autoScroll;
        d->autoScroll = false;
        d->selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
        d->autoScroll = autoScroll;
        QRect rect(d->pressedPosition - offset, pos);
        setSelection(rect, command);

        // signal handlers may change the model
        emit pressed(index);
        if (d->autoScroll) {
            //we delay the autoscrolling to filter out double click event
            //100 is to be sure that there won't be a double-click misinterpreted as a 2 single clicks
            d->delayedAutoScroll.start(QApplication::doubleClickInterval()+100, this);
        }

    } else {
        // Forces a finalize() even if mouse is pressed, but not on a item
        d->selectionModel->select(QModelIndex(), QItemSelectionModel::Select);
    }
}

/*!
    This function is called with the given \a event when a mouse move event is
    sent to the widget. If a selection is in progress and new items are moved
    over the selection is extended; if a drag is in progress it is continued.
*/
void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
{
    Q_D(QAbstractItemView);
    QPoint topLeft;
    QPoint bottomRight = event->pos();

    if (state() == ExpandingState || state() == CollapsingState)
        return;

#ifndef QT_NO_DRAGANDDROP
    if (state() == DraggingState) {
        topLeft = d->pressedPosition - d->offset();
        if ((topLeft - bottomRight).manhattanLength() > QApplication::startDragDistance()) {
            d->pressedIndex = QModelIndex();
            startDrag(d->model->supportedDragActions());
            setState(NoState); // the startDrag will return when the dnd operation is done
            stopAutoScroll();
        }
        return;
    }
#endif // QT_NO_DRAGANDDROP

    QPersistentModelIndex index = indexAt(bottomRight);
    QModelIndex buddy = d->model->buddy(d->pressedIndex);
    if ((state() == EditingState && d->hasEditor(buddy))
        || edit(index, NoEditTriggers, event))
        return;

    if (d->selectionMode != SingleSelection)
        topLeft = d->pressedPosition - d->offset();
    else
        topLeft = bottomRight;

    d->checkMouseMove(index);

#ifndef QT_NO_DRAGANDDROP
    if (d->pressedIndex.isValid()
        && d->dragEnabled
        && (state() != DragSelectingState)
        && (event->buttons() != Qt::NoButton)
        && !d->selectedDraggableIndexes().isEmpty()) {
            setState(DraggingState);
            return;
    }
#endif

    if ((event->buttons() & Qt::LeftButton) && d->selectionAllowed(index) && d->selectionModel) {
        setState(DragSelectingState);
        QItemSelectionModel::SelectionFlags command = selectionCommand(index, event);

        // Do the normalize ourselves, since QRect::normalized() is flawed
        QRect selectionRect = QRect(topLeft, bottomRight);
        setSelection(selectionRect, command);

        // set at the end because it might scroll the view
        if (index.isValid()
            && (index != d->selectionModel->currentIndex())
            && d->isIndexEnabled(index))
            d->selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
    }
}

/*!
    This function is called with the given \a event when a mouse button is released,
    after a mouse press event on the widget. If a user presses the mouse inside your
    widget and then drags the mouse to another location before releasing the mouse button,
    your widget receives the release event. The function will emit the clicked() signal if an
    item was being pressed.
*/
void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event)
{
    Q_D(QAbstractItemView);

    QPoint pos = event->pos();
    QPersistentModelIndex index = indexAt(pos);

    if (state() == EditingState) {
        if (d->isIndexValid(index)
            && d->isIndexEnabled(index)
            && d->sendDelegateEvent(index, event))
            update(index);
        return;
    }

    bool click = (index == d->pressedIndex && index.isValid());
    bool selectedClicked = click && (event->button() & Qt::LeftButton) && d->pressedAlreadySelected;
    EditTrigger trigger = (selectedClicked ? SelectedClicked : NoEditTriggers);
    bool edited = edit(index, trigger, event);

    if (d->selectionModel)
        d->selectionModel->select(index, selectionCommand(index, event));

    setState(NoState);

    if (click) {
        emit clicked(index);
        if (edited)
            return;
        if (style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, 0, this))
            emit activated(index);
    }
}

/*!
    This function is called with the given \a event when a mouse button is
    double clicked inside the widget. If the double-click is on a valid item it
    emits the doubleClicked() signal and calls edit() on the item.
*/
void QAbstractItemView::mouseDoubleClickEvent(QMouseEvent *event)
{
    Q_D(QAbstractItemView);

    QModelIndex index = indexAt(event->pos());
    if (!index.isValid()
        || !d->isIndexEnabled(index)
        || (d->pressedIndex != index)) {
        QMouseEvent me(QEvent::MouseButtonPress,
                       event->pos(), event->button(),
                       event->buttons(), event->modifiers());
        mousePressEvent(&me);
        return;
    }
    // signal handlers may change the model
    QPersistentModelIndex persistent = index;
    emit doubleClicked(persistent);
    if ((event->button() & Qt::LeftButton) && !edit(persistent, DoubleClicked, event)
        && !style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, 0, this))
        emit activated(persistent);
}

#ifndef QT_NO_DRAGANDDROP

/*!
    This function is called with the given \a event when a drag and drop operation enters
    the widget. If the drag is over a valid dropping place (e.g. over an item that
    accepts drops), the event is accepted; otherwise it is ignored.

    \sa dropEvent() startDrag()
*/
void QAbstractItemView::dragEnterEvent(QDragEnterEvent *event)
{
    if (dragDropMode() == InternalMove
        && (event->source() != this|| !(event->possibleActions() & Qt::MoveAction)))
        return;

    if (d_func()->canDecode(event)) {
        event->accept();
        setState(DraggingState);
    } else {
        event->ignore();
    }
}

/*!
    This function is called continuously with the given \a event during a drag and
    drop operation over the widget. It can cause the view to scroll if, for example,
    the user drags a selection to view's right or bottom edge. In this case, the
    event will be accepted; otherwise it will be ignored.

    \sa dropEvent() startDrag()
*/
void QAbstractItemView::dragMoveEvent(QDragMoveEvent *event)
{
    Q_D(QAbstractItemView);
    if (dragDropMode() == InternalMove
        && (event->source() != this || !(event->possibleActions() & Qt::MoveAction)))
        return;

    // ignore by default
    event->ignore();

    QModelIndex index = indexAt(event->pos());
    d->hover = index;
    if (!d->droppingOnItself(event, index)
        && d->canDecode(event)) {

        if (index.isValid() && d->showDropIndicator) {
            QRect rect = visualRect(index);
            d->dropIndicatorPosition = d->position(event->pos(), rect, index);
            switch (d->dropIndicatorPosition) {
            case AboveItem:
                if (d->isIndexDropEnabled(index.parent())) {
                    d->dropIndicatorRect = QRect(rect.left(), rect.top(), rect.width(), 0);
                    event->accept();
                } else {
                    d->dropIndicatorRect = QRect();
                }
                break;
            case BelowItem:
                if (d->isIndexDropEnabled(index.parent())) {
                    d->dropIndicatorRect = QRect(rect.left(), rect.bottom(), rect.width(), 0);
                    event->accept();
                } else {
                    d->dropIndicatorRect = QRect();
                }
                break;
            case OnItem:
                if (d->isIndexDropEnabled(index)) {
                    d->dropIndicatorRect = rect;
                    event->accept();
                } else {
                    d->dropIndicatorRect = QRect();
                }
                break;
            case OnViewport:
                d->dropIndicatorRect = QRect();
                if (d->isIndexDropEnabled(rootIndex())) {
                    event->accept(); // allow dropping in empty areas
                }
                break;
            }
        } else {
            d->dropIndicatorRect = QRect();
            d->dropIndicatorPosition = OnViewport;
            if (d->isIndexDropEnabled(rootIndex())) {
                event->accept(); // allow dropping in empty areas
            }
        }
        d->viewport->update();
    } // can decode

    if (d->shouldAutoScroll(event->pos()))
        startAutoScroll();
}

/*!
    \internal
    Return true if this is a move from ourself and \a index is a child of the selection that
    is being moved.
 */
bool QAbstractItemViewPrivate::droppingOnItself(QDropEvent *event, const QModelIndex &index)
{
    Q_Q(QAbstractItemView);
    Qt::DropAction dropAction = event->dropAction();
    if (q->dragDropMode() == QAbstractItemView::InternalMove)
        dropAction = Qt::MoveAction;
    if (event->source() == q
        && event->possibleActions() & Qt::MoveAction
        && dropAction == Qt::MoveAction) {
        QModelIndexList selectedIndexes = q->selectedIndexes();
        QModelIndex child = index;
        while (child.isValid() && child != root) {
            if (selectedIndexes.contains(child))
                return true;
            child = child.parent();
        }
    }
    return false;
}

/*!
    \fn void QAbstractItemView::dragLeaveEvent(QDragLeaveEvent *event)

    This function is called when the item being dragged leaves the view.
    The \a event describes the state of the drag and drop operation.
*/
void QAbstractItemView::dragLeaveEvent(QDragLeaveEvent *)
{
    Q_D(QAbstractItemView);
    stopAutoScroll();
    setState(NoState);
    d->hover = QModelIndex();
    d->viewport->update();
}

/*!
    This function is called with the given \a event when a drop event occurs over
    the widget. If the model accepts the even position the drop event is accepted;
    otherwise it is ignored.

    \sa startDrag()
*/
void QAbstractItemView::dropEvent(QDropEvent *event)
{
    Q_D(QAbstractItemView);
    if (dragDropMode() == InternalMove) {
        if (event->source() != this || !(event->possibleActions() & Qt::MoveAction))
            return;
    }

    QModelIndex index;
    int col = -1;
    int row = -1;
    if (d->dropOn(event, &row, &col, &index)) {
        if (d->model->dropMimeData(event->mimeData(),
            dragDropMode() == InternalMove ? Qt::MoveAction : event->dropAction(), row, col, index)) {
                if (dragDropMode() == InternalMove)
                    event->setDropAction(Qt::MoveAction);
                event->accept();
        }
    }
    stopAutoScroll();
    setState(NoState);
    d->viewport->update();
}

/*!
    If the event hasn't already been accepted, determines the index to drop on.

    if (row == -1 && col == -1)
        // append to this drop index
    else
        // place at row, col in drop index

    If it returns true a drop can be done, and dropRow, dropCol and dropIndex reflects the position of the drop.
    \internal
  */
bool QAbstractItemViewPrivate::dropOn(QDropEvent *event, int *dropRow, int *dropCol, QModelIndex *dropIndex)
{
    Q_Q(QAbstractItemView);
    if (event->isAccepted())
        return false;

    QModelIndex index;
    // rootIndex() (i.e. the viewport) might be a valid index
    if (viewport->rect().contains(event->pos())) {
        index = q->indexAt(event->pos());
        if (!index.isValid() || !q->visualRect(index).contains(event->pos()))
            index = root;
    }

    // If we are allowed to do the drop
    if (model->supportedDropActions() & event->dropAction()) {
        int row = -1;
        int col = -1;
        if (index != root) {
            dropIndicatorPosition = position(event->pos(), q->visualRect(index), index);
            switch (dropIndicatorPosition) {
            case QAbstractItemView::AboveItem:
                row = index.row();
                col = index.column();
                index = index.parent();
                break;
            case QAbstractItemView::BelowItem:
                row = index.row() + 1;
                col = index.column();
                index = index.parent();
                break;
            case QAbstractItemView::OnItem:
            case QAbstractItemView::OnViewport:
                break;
            }
        } else {
            dropIndicatorPosition = QAbstractItemView::OnViewport;
        }
        *dropIndex = index;
        *dropRow = row;
        *dropCol = col;
        if (!droppingOnItself(event, index))
            return true;
    }
    return false;
}

QAbstractItemView::DropIndicatorPosition
QAbstractItemViewPrivate::position(const QPoint &pos, const QRect &rect, const QModelIndex &index) const
{
    QAbstractItemView::DropIndicatorPosition r = QAbstractItemView::OnViewport;
    if (!overwrite) {
        const int margin = 2;
        if (pos.y() - rect.top() < margin) {
            r = QAbstractItemView::AboveItem;
        } else if (rect.bottom() - pos.y() < margin) {
            r = QAbstractItemView::BelowItem;
        } else if (rect.contains(pos, true)) {
            r = QAbstractItemView::OnItem;
        }
    } else {
        QRect touchingRect = rect;
        touchingRect.adjust(-1, -1, 1, 1);
        if (touchingRect.contains(pos, false)) {
            r = QAbstractItemView::OnItem;
        }
    }

    if (r == QAbstractItemView::OnItem && (!(model->flags(index) & Qt::ItemIsDropEnabled)))
        r = pos.y() < rect.center().y() ? QAbstractItemView::AboveItem : QAbstractItemView::BelowItem;

    return r;
}

#endif // QT_NO_DRAGANDDROP

/*!
    This function is called with the given \a event when the widget obtains the focus.
    By default, the event is ignored.

    \sa setFocus(), focusOutEvent()
*/
void QAbstractItemView::focusInEvent(QFocusEvent *event)
{
    Q_D(QAbstractItemView);
    QAbstractScrollArea::focusInEvent(event);
    if (selectionModel()
        && !d->currentIndexSet
        && !currentIndex().isValid()) {
        bool autoScroll = d->autoScroll;
        d->autoScroll = false;
        QModelIndex index = moveCursor(MoveNext, Qt::NoModifier); // first visible index
        if (index.isValid() && d->isIndexEnabled(index))
            selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
        d->autoScroll = autoScroll;
    }
    d->viewport->update();
}

/*!
    This function is called with the given \a event when the widget
    looses the focus. By default, the event is ignored.

    \sa clearFocus(), focusInEvent()
*/
void QAbstractItemView::focusOutEvent(QFocusEvent *event)
{
    Q_D(QAbstractItemView);
    QAbstractScrollArea::focusOutEvent(event);
    d->viewport->update();
}

/*!
    This function is called with the given \a event when a key event is sent to
    the widget. The default implementation handles basic cursor movement, e.g. Up,
    Down, Left, Right, Home, PageUp, and PageDown; the activated() signal is
    emitted if the current index is valid and the activation key is pressed
    (e.g. Enter or Return, depending on the platform).
    This function is where editing is initiated by key press, e.g. if F2 is
    pressed.

    \sa edit(), moveCursor(), keyboardSearch(), tabKeyNavigation
*/
void QAbstractItemView::keyPressEvent(QKeyEvent *event)
{
    Q_D(QAbstractItemView);
    d->delayedAutoScroll.stop(); //any interaction with the view cancel the auto scrolling

#ifdef QT_KEYPAD_NAVIGATION
    switch (event->key()) {
    case Qt::Key_Select:
        if (QApplication::keypadNavigationEnabled()) {
            if (!hasEditFocus()) {
                setEditFocus(true);
                return;
            }
        }
        break;
    case Qt::Key_Back:
        if (QApplication::keypadNavigationEnabled() && hasEditFocus())
            setEditFocus(false);
        else
            event->ignore();
        return;
    default:
        if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
            event->ignore();
            return;
        }
    }
#endif

#if !defined(QT_NO_CLIPBOARD) && !defined(QT_NO_SHORTCUT)
    if (event == QKeySequence::Copy) {
        QVariant variant;
        if (d->model)
            variant = d->model->data(currentIndex(), Qt::DisplayRole);
        if (variant.type() == QVariant::String)
            QApplication::clipboard()->setText(variant.toString());
        event->accept();
    }
#endif

    QPersistentModelIndex newCurrent;
    switch (event->key()) {
    case Qt::Key_Down:
        newCurrent = moveCursor(MoveDown, event->modifiers());
        break;
    case Qt::Key_Up:
        newCurrent = moveCursor(MoveUp, event->modifiers());
        break;
    case Qt::Key_Left:
        newCurrent = moveCursor(MoveLeft, event->modifiers());
        break;
    case Qt::Key_Right:
        newCurrent = moveCursor(MoveRight, event->modifiers());
        break;
    case Qt::Key_Home:
        newCurrent = moveCursor(MoveHome, event->modifiers());
        break;
    case Qt::Key_End:
        newCurrent = moveCursor(MoveEnd, event->modifiers());
        break;
    case Qt::Key_PageUp:
        newCurrent = moveCursor(MovePageUp, event->modifiers());
        break;
    case Qt::Key_PageDown:
        newCurrent = moveCursor(MovePageDown, event->modifiers());
        break;
    case Qt::Key_Tab:
        if (d->tabKeyNavigation)
            newCurrent = moveCursor(MoveNext, event->modifiers());
        break;
    case Qt::Key_Backtab:
        if (d->tabKeyNavigation)
            newCurrent = moveCursor(MovePrevious, event->modifiers());
        break;
    }

    QPersistentModelIndex oldCurrent = currentIndex();
    if (newCurrent != oldCurrent && newCurrent.isValid() && d->isIndexEnabled(newCurrent)) {
        if (!hasFocus() && QApplication::focusWidget() == indexWidget(oldCurrent))
            setFocus();
        QItemSelectionModel::SelectionFlags command = selectionCommand(newCurrent, event);
        if (command != QItemSelectionModel::NoUpdate
             || style()->styleHint(QStyle::SH_ItemView_MovementWithoutUpdatingSelection, 0, this)) {
            // note that we don't check if the new current index is enabled because moveCursor() makes sure it is
            if (command & QItemSelectionModel::Current) {
                d->selectionModel->setCurrentIndex(newCurrent, QItemSelectionModel::NoUpdate);
                if (d->pressedPosition == QPoint(-1, -1))
                    d->pressedPosition = visualRect(oldCurrent).center();
                QRect rect(d->pressedPosition - d->offset(), visualRect(newCurrent).center());
                setSelection(rect, command);
            } else {
                d->selectionModel->setCurrentIndex(newCurrent, command);
                d->pressedPosition = visualRect(newCurrent).center() + d->offset();
            }
            return;
        }
    }

    switch (event->key()) {
    // ignored keys
    case Qt::Key_Down:
    case Qt::Key_Up:
#ifdef QT_KEYPAD_NAVIGATION
        if (QApplication::keypadNavigationEnabled()) {
            event->accept(); // don't change focus
            break;
        }
#endif
    case Qt::Key_Left:
    case Qt::Key_Right:
    case Qt::Key_Home:
    case Qt::Key_End:
    case Qt::Key_PageUp:
    case Qt::Key_PageDown:
    case Qt::Key_Escape:
    case Qt::Key_Shift:
    case Qt::Key_Control:
        event->ignore();
        break;
    case Qt::Key_Space:
    case Qt::Key_Select:
        if (!edit(currentIndex(), AnyKeyPressed, event) && d->selectionModel)
            d->selectionModel->select(currentIndex(), selectionCommand(currentIndex(), event));
#ifdef QT_KEYPAD_NAVIGATION
        if ( event->key()==Qt::Key_Select ) {
            // Also do Key_Enter action.
            if (currentIndex().isValid()) {
                if (state() != EditingState)
                    emit activated(currentIndex());
            } else {
                event->ignore();
            }
        }
#endif
        break;
#ifdef Q_WS_MAC
    case Qt::Key_Enter:
    case Qt::Key_Return:
        // Propagate the enter if you couldn't edit the item and there are no
        // current editors (if there are editors, the event was most likely propagated from it).
        if (!edit(currentIndex(), EditKeyPressed, event) && d->editors.isEmpty())
            event->ignore();
        break;
#else
    case Qt::Key_F2:
        if (!edit(currentIndex(), EditKeyPressed, event))
            event->ignore();
        break;
    case Qt::Key_Enter:
    case Qt::Key_Return:
        // ### we can't open the editor on enter, becuse
        // some widgets will forward the enter event back
        // to the viewport, starting an endless loop
        if (state() != EditingState || hasFocus()) {
            if (currentIndex().isValid())
                emit activated(currentIndex());
            event->ignore();
        }
        break;
#endif
    case Qt::Key_A:
        if (event->modifiers() & Qt::ControlModifier) {
            selectAll();
            break;
        }
    default: {
#ifdef Q_WS_MAC
        if (event->key() == Qt::Key_O && event->modifiers() & Qt::ControlModifier && currentIndex().isValid()) {
            emit activated(currentIndex());
            break;
        }
#endif
        bool modified = (event->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier));
        if (!event->text().isEmpty() && !modified && !edit(currentIndex(), AnyKeyPressed, event)) {
            keyboardSearch(event->text());
            event->accept();
        } else {
            event->ignore();
        }
        break; }
    }
}

/*!
    This function is called with the given \a event when a resize event is sent to
    the widget.

    \sa QWidget::resizeEvent()
*/
void QAbstractItemView::resizeEvent(QResizeEvent *event)
{
    QAbstractScrollArea::resizeEvent(event);
    updateGeometries();
}

/*!
  This function is called with the given \a event when a timer event is sent
  to the widget.

  \sa QObject::timerEvent()
*/
void QAbstractItemView::timerEvent(QTimerEvent *event)
{
    Q_D(QAbstractItemView);
    if (event->timerId() == d->fetchMoreTimer.timerId())
        d->fetchMore();
    if (event->timerId() == d->autoScrollTimer.timerId())
        doAutoScroll();
    else if (event->timerId() == d->updateTimer.timerId())
        d->updateDirtyRegion();
    else if (event->timerId() == d->delayedEditing.timerId()) {
        d->delayedEditing.stop();
        edit(currentIndex());
    } else if (event->timerId() == d->delayedLayout.timerId()) {
        d->delayedLayout.stop();
        if (isVisible()) {
            d->interruptDelayedItemsLayout();
            doItemsLayout();
            const QModelIndex current = currentIndex();
            if (current.isValid() && d->state == QAbstractItemView::EditingState)
                scrollTo(current);
        }
    } else if (event->timerId() == d->delayedAutoScroll.timerId()) {
        d->delayedAutoScroll.stop();
        //end of the timer: if the current item is still the same as the one when the mouse press occurred
        //we only get here if there was no double click
        if (d->pressedIndex.isValid() && d->pressedIndex == currentIndex())
            scrollTo(d->pressedIndex);
    }
}

/*!
    \reimp
*/
void QAbstractItemView::inputMethodEvent(QInputMethodEvent *event)
{
    if (event->commitString().isEmpty() && event->preeditString().isEmpty()) {
        event->ignore();
        return;
    }
    if (!edit(currentIndex(), AnyKeyPressed, event)) {
        if (!event->commitString().isEmpty())
            keyboardSearch(event->commitString());
        event->ignore();
    }
}

#ifndef QT_NO_DRAGANDDROP
/*!
    \enum QAbstractItemView::DropIndicatorPosition

    This enum indicates the position of the drop indicator in
    relation to the index at the current mouse position:

    \value OnItem  The item will be dropped on the index.

    \value AboveItem  The item will be dropped above the index.

    \value BelowItem  The item will be dropped below the index.

    \value OnViewport  The item will be dropped onto a region of the viewport with
no items. The way each view handles items dropped onto the viewport depends on
the behavior of the underlying model in use.
*/


/*!
    \since 4.1

    Returns the position of the drop indicator in relation to the closest item.
*/
QAbstractItemView::DropIndicatorPosition QAbstractItemView::dropIndicatorPosition() const
{
    Q_D(const QAbstractItemView);
    return d->dropIndicatorPosition;
}
#endif

/*!
  This convenience function returns a list of all selected and
  non-hidden item indexes in the view. The list contains no
  duplicates, and is not sorted.

  \sa QItemSelectionModel::selectedIndexes()
*/
QModelIndexList QAbstractItemView::selectedIndexes() const
{
    Q_D(const QAbstractItemView);
    QModelIndexList indexes;
    if (d->selectionModel) {
        indexes = d->selectionModel->selectedIndexes();
        QList<QModelIndex>::iterator it = indexes.begin();
        while (it != indexes.end())
            if (isIndexHidden(*it))
                it = indexes.erase(it);
            else
                ++it;
    }
    return indexes;
}

/*!
    Starts editing the item at \a index, creating an editor if
    necessary, and returns true if the view's \l{State} is now
    EditingState; otherwise returns false.

    The action that caused the editing process is described by
    \a trigger, and the associated event is specified by \a event.

    Editing can be forced by specifying the \a trigger to be
    QAbstractItemView::AllEditTriggers.

    \sa closeEditor()
*/
bool QAbstractItemView::edit(const QModelIndex &index, EditTrigger trigger, QEvent *event)
{
    Q_D(QAbstractItemView);

    if (!d->isIndexValid(index))
        return false;

    if (QWidget *w = (d->persistent.isEmpty() ? static_cast<QWidget*>(0) : d->editorForIndex(index).editor.data())) {
        if (w->focusPolicy() == Qt::NoFocus)
            return false;
        w->setFocus();
        return true;
    }

    if (trigger == DoubleClicked) {
        d->delayedEditing.stop();
        d->delayedAutoScroll.stop();
    } else if (trigger == CurrentChanged) {
        d->delayedEditing.stop();
    }

    if (d->sendDelegateEvent(index, event)) {
        update(index);
        return true;
    }

    // save the previous trigger before updating
    EditTriggers lastTrigger = d->lastTrigger;
    d->lastTrigger = trigger;

    if (!d->shouldEdit(trigger, d->model->buddy(index)))
        return false;

    if (d->delayedEditing.isActive())
        return false;

    // we will receive a mouseButtonReleaseEvent after a
    // mouseDoubleClickEvent, so we need to check the previous trigger
    if (lastTrigger == DoubleClicked && trigger == SelectedClicked)
        return false;

    // we may get a double click event later
    if (trigger == SelectedClicked)
        d->delayedEditing.start(QApplication::doubleClickInterval(), this);
    else
        d->openEditor(index, d->shouldForwardEvent(trigger, event) ? event : 0);

    return true;
}

/*!
  \internal
  Updates the data shown in the open editor widgets in the view.
*/
void QAbstractItemView::updateEditorData()
{
    Q_D(QAbstractItemView);
    d->updateEditorData(QModelIndex(), QModelIndex());
}

/*!
  \internal
   Updates the geometry of the open editor widgets in the view.
*/
void QAbstractItemView::updateEditorGeometries()
{
    Q_D(QAbstractItemView);
    if(d->editors.isEmpty())
        return;
    QStyleOptionViewItemV4 option = d->viewOptionsV4();
    QList<QEditorInfo>::iterator it = d->editors.begin();
    QWidgetList editorsToRelease;
    while (it != d->editors.end()) {
        QModelIndex index = it->index;
        QWidget *editor = it->editor;
        if (index.isValid() && editor) {
            option.rect = visualRect(index);
            if (option.rect.isValid()) {
                editor->show();
                QAbstractItemDelegate *delegate = d->delegateForIndex(index);
                if (delegate)
                    delegate->updateEditorGeometry(editor, option, index);
            } else {
                editor->hide();
            }
            ++it;
        } else {
            it = d->editors.erase(it);
            editorsToRelease << editor;
        }
    }

    //we release the editor outside of the loop because it might change the focus and try
    //to change the d->editors list.
    for (int i = 0; i < editorsToRelease.count(); ++i) {
        d->releaseEditor(editorsToRelease.at(i));
    }
}

/*!
    \since 4.4

    Updates the geometry of the child widgets of the view.
*/
void QAbstractItemView::updateGeometries()
{
    updateEditorGeometries();
    d_func()->fetchMoreTimer.start(0, this); //fetch more later
}

/*!
  \internal
*/
void QAbstractItemView::verticalScrollbarValueChanged(int value)
{
    Q_D(QAbstractItemView);
    if (verticalScrollBar()->maximum() == value && d->model->canFetchMore(d->root))
        d->model->fetchMore(d->root);
    d->checkMouseMove(viewport()->mapFromGlobal(QCursor::pos()));
}

/*!
  \internal
*/
void QAbstractItemView::horizontalScrollbarValueChanged(int value)
{
    Q_D(QAbstractItemView);
    if (horizontalScrollBar()->maximum() == value && d->model->canFetchMore(d->root))
        d->model->fetchMore(d->root);
    d->checkMouseMove(viewport()->mapFromGlobal(QCursor::pos()));
}

/*!
    \internal
*/
void QAbstractItemView::verticalScrollbarAction(int)
{
    //do nothing
}

/*!
    \internal
*/
void QAbstractItemView::horizontalScrollbarAction(int)
{
    //do nothing
}

/*!
    Closes the given \a editor, and releases it. The \a hint is
    used to specify how the view should respond to the end of the editing
    operation. For example, the hint may indicate that the next item in
    the view should be opened for editing.

    \sa edit(), commitData()
*/

void QAbstractItemView::closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint)
{
    Q_D(QAbstractItemView);

    // Close the editor
    if (editor) {
        bool isPersistent = d->persistent.contains(editor);
        bool hadFocus = editor->hasFocus();
        QModelIndex index = d->indexForEditor(editor);
        if (!index.isValid())
            return; // the editor was not registered

        if (!isPersistent) {
            setState(NoState);
            QModelIndex index = d->indexForEditor(editor);
            editor->removeEventFilter(d->delegateForIndex(index));
            d->removeEditor(editor);
        }
        if (hadFocus)
            setFocus(); // this will send a focusLost event to the editor
        else
            d->checkPersistentEditorFocus();

        QPointer<QWidget> ed = editor;
        QApplication::sendPostedEvents(editor, 0);
        editor = ed;

        if (!isPersistent && editor)
            d->releaseEditor(editor);
    }

    // The EndEditHint part
    QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::ClearAndSelect
                                                | d->selectionBehaviorFlags();
    switch (hint) {
    case QAbstractItemDelegate::EditNextItem: {
        QModelIndex index = moveCursor(MoveNext, Qt::NoModifier);
        if (index.isValid()) {
            QPersistentModelIndex persistent(index);
            d->selectionModel->setCurrentIndex(persistent, flags);
            // currentChanged signal would have already started editing
            if (index.flags() & Qt::ItemIsEditable
                && (!(editTriggers() & QAbstractItemView::CurrentChanged)))
                edit(persistent);
        } break; }
    case QAbstractItemDelegate::EditPreviousItem: {
        QModelIndex index = moveCursor(MovePrevious, Qt::NoModifier);
        if (index.isValid()) {
            QPersistentModelIndex persistent(index);
            d->selectionModel->setCurrentIndex(persistent, flags);
            // currentChanged signal would have already started editing
            if (index.flags() & Qt::ItemIsEditable
                && (!(editTriggers() & QAbstractItemView::CurrentChanged)))
                edit(persistent);
        } break; }
    case QAbstractItemDelegate::SubmitModelCache:
        d->model->submit();
        break;
    case QAbstractItemDelegate::RevertModelCache:
        d->model->revert();
        break;
    default:
        break;
    }
}

/*!
  Commit the data in the \a editor to the model.

  \sa closeEditor()
*/
void QAbstractItemView::commitData(QWidget *editor)
{
    Q_D(QAbstractItemView);
    if (!editor || !d->itemDelegate || d->currentlyCommittingEditor)
        return;
    QModelIndex index = d->indexForEditor(editor);
    if (!index.isValid())
        return;
    d->currentlyCommittingEditor = editor;
    QAbstractItemDelegate *delegate = d->delegateForIndex(index);
    editor->removeEventFilter(delegate);
    delegate->setModelData(editor, d->model, index);
    editor->installEventFilter(delegate);
    d->currentlyCommittingEditor = 0;
}

/*!
  This function is called when the given \a editor has been destroyed.

  \sa closeEditor()
*/
void QAbstractItemView::editorDestroyed(QObject *editor)
{
    Q_D(QAbstractItemView);
    QWidget *w = qobject_cast<QWidget*>(editor);
    d->removeEditor(w);
    d->persistent.remove(w);
    if (state() == EditingState)
        setState(NoState);
}

/*!
    \obsolete
    Sets the horizontal scroll bar's steps per item to \a steps.

    This is the number of steps used by the horizontal scroll bar to
    represent the width of an item.

    Note that if the view has a horizontal header, the item steps
    will be ignored and the header section size will be used instead.

    \sa horizontalStepsPerItem() setVerticalStepsPerItem()
*/
void QAbstractItemView::setHorizontalStepsPerItem(int steps)
{
    Q_UNUSED(steps);
    // do nothing
}

/*!
    \obsolete
    Returns the horizontal scroll bar's steps per item.

    \sa setHorizontalStepsPerItem() verticalStepsPerItem()
*/
int QAbstractItemView::horizontalStepsPerItem() const
{
    return 1;
}

/*!
    \obsolete
    Sets the vertical scroll bar's steps per item to \a steps.

    This is the number of steps used by the vertical scroll bar to
    represent the height of an item.

    Note that if the view has a vertical header, the item steps
    will be ignored and the header section size will be used instead.

    \sa verticalStepsPerItem() setHorizontalStepsPerItem()
*/
void QAbstractItemView::setVerticalStepsPerItem(int steps)
{
    Q_UNUSED(steps);
    // do nothing
}

/*!
    \obsolete
    Returns the vertical scroll bar's steps per item.

    \sa setVerticalStepsPerItem() horizontalStepsPerItem()
*/
int QAbstractItemView::verticalStepsPerItem() const
{
    return 1;
}

/*!
  Moves to and selects the item best matching the string \a search.
  If no item is found nothing happens.

  In the default implementation, the search is reset if \a search is empty, or
  the time interval since the last search has exceeded
  QApplication::keyboardInputInterval().
*/
void QAbstractItemView::keyboardSearch(const QString &search)
{
    Q_D(QAbstractItemView);
    if (!d->model->rowCount(d->root) || !d->model->columnCount(d->root))
        return;

    QModelIndex start = currentIndex().isValid() ? currentIndex()
                        : d->model->index(0, 0, d->root);
    QTime now(QTime::currentTime());
    bool skipRow = false;
    if (search.isEmpty()
        || (d->keyboardInputTime.msecsTo(now) > QApplication::keyboardInputInterval())) {
        d->keyboardInput = search;
        skipRow = true;
    } else {
        d->keyboardInput += search;
    }
    d->keyboardInputTime = now;

    // special case for searches with same key like 'aaaaa'
    bool sameKey = false;
    if (d->keyboardInput.length() > 1) {
        int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.length() - 1));
        sameKey = (c == d->keyboardInput.length());
        if (sameKey)
            skipRow = true;
    }

    // skip if we are searching for the same key or a new search started
    if (skipRow) {
        QModelIndex parent = start.parent();
        int newRow = (start.row() < d->model->rowCount(parent) - 1) ? start.row() + 1 : 0;
        start = d->model->index(newRow, start.column(), parent);
    }

    // search from start with wraparound
    const QString searchString = sameKey ? QString(d->keyboardInput.at(0)) : d->keyboardInput;
    QModelIndex current = start;
    QModelIndexList match;
    QModelIndex firstMatch;
    QModelIndexList previous;
    do {
        match = d->model->match(current, Qt::DisplayRole, searchString);
        if (match == previous)
            break;
        firstMatch = match.value(0);
        previous = match;
        if (firstMatch.isValid()) {
            if (d->isIndexEnabled(firstMatch)) {
                setCurrentIndex(firstMatch);
                break;
            }
	    int row = firstMatch.row() + 1;
	    if (row >= d->model->rowCount(firstMatch.parent()))
	        row = 0;
            current = firstMatch.sibling(row, firstMatch.column());
        }
    } while (current != start && firstMatch.isValid());
}

/*!
    Returns the size hint for the item with the specified \a index or
    an invalid size for invalid indexes.

    \sa sizeHintForRow(), sizeHintForColumn()
*/
QSize QAbstractItemView::sizeHintForIndex(const QModelIndex &index) const
{
    Q_D(const QAbstractItemView);
    if (!d->isIndexValid(index) || !d->itemDelegate)
        return QSize();
    return d->delegateForIndex(index)->sizeHint(d->viewOptionsV4(), index);
}

/*!
    Returns the height size hint for the specified \a row or -1 if
    there is no model.

    The returned height is calculated using the size hints of the
    given \a row's items, i.e. the returned value is the maximum
    height among the items. Note that to control the height of a row,
    you must reimplement the QAbstractItemDelegate::sizeHint()
    function.

    This function is used in views with a vertical header to find the
    size hint for a header section based on the contents of the given
    \a row.

    \sa sizeHintForColumn()
*/
int QAbstractItemView::sizeHintForRow(int row) const
{
    Q_D(const QAbstractItemView);

    if (row < 0 || row >= d->model->rowCount() || !model())
        return -1;

    QStyleOptionViewItemV4 option = d->viewOptionsV4();
    int height = 0;
    int colCount = d->model->columnCount(d->root);
    QModelIndex index;
    for (int c = 0; c < colCount; ++c) {
        index = d->model->index(row, c, d->root);
        if (QWidget *editor = d->editorForIndex(index).editor)
            height = qMax(height, editor->size().height());
        int hint = d->delegateForIndex(index)->sizeHint(option, index).height();
        height = qMax(height, hint);
    }
    return height;
}

/*!
    Returns the width size hint for the specified \a column or -1 if there is no model.

    This function is used in views with a horizontal header to find the size hint for
    a header section based on the contents of the given \a column.

    \sa sizeHintForRow()
*/
int QAbstractItemView::sizeHintForColumn(int column) const
{
    Q_D(const QAbstractItemView);

    if (column < 0 || column >= d->model->columnCount() || !model())
        return -1;

    QStyleOptionViewItemV4 option = d->viewOptionsV4();
    int width = 0;
    int rows = d->model->rowCount(d->root);
    QModelIndex index;
    for (int r = 0; r < rows; ++r) {
        index = d->model->index(r, column, d->root);
        if (QWidget *editor = d->editorForIndex(index).editor)
            width = qMax(width, editor->sizeHint().width());
        int hint = d->delegateForIndex(index)->sizeHint(option, index).width();
        width = qMax(width, hint);
    }
    return width;
}

/*!
    Opens a persistent editor on the item at the given \a index.
    If no editor exists, the delegate will create a new editor.

    \sa closePersistentEditor()
*/
void QAbstractItemView::openPersistentEditor(const QModelIndex &index)
{
    Q_D(QAbstractItemView);
    QStyleOptionViewItemV4 options = d->viewOptionsV4();
    options.rect = visualRect(index);
    options.state |= (index == currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);

    QWidget *editor = d->editor(index, options);
    if (editor) {
        editor->show();
        d->persistent.insert(editor);
    }
}

/*!
  Closes the persistent editor for the item at the given \a index.

  \sa openPersistentEditor()
*/
void QAbstractItemView::closePersistentEditor(const QModelIndex &index)
{
    Q_D(QAbstractItemView);
    QWidget *editor = d->editorForIndex(index).editor;
    if (editor) {
        if (index == selectionModel()->currentIndex())
            closeEditor(editor, QAbstractItemDelegate::RevertModelCache);
        d->persistent.remove(editor);
        d->removeEditor(editor);
        d->releaseEditor(editor);
    }
}

/*!
    \since 4.1

    Sets the given \a widget on the item at the given \a index, passing the
    ownership of the widget to the viewport.

    If \a index is invalid (e.g., if you pass the root index), this function
    will do nothing.

    The given \a widget's \l{QWidget}{autoFillBackground} property must be set
    to true, otherwise the widget's background will be transparent, showing
    both the model data and the item at the given \a index.

    If index widget A is replaced with index widget B, index widget A will be
    deleted. For example, in the code snippet below, the QLineEdit object will
    be deleted.

    \snippet doc/src/snippets/code/src_gui_itemviews_qabstractitemview.cpp 1

    This function should only be used to display static content within the
    visible area corresponding to an item of data. If you want to display
    custom dynamic content or implement a custom editor widget, subclass
    QItemDelegate instead.

    \sa {Delegate Classes}
*/
void QAbstractItemView::setIndexWidget(const QModelIndex &index, QWidget *widget)
{
    Q_D(QAbstractItemView);
    if (!d->isIndexValid(index))
        return;
    if (QWidget *oldWidget = indexWidget(index)) {
        d->removeEditor(oldWidget);
        oldWidget->deleteLater();
    }
    if (widget) {
        widget->setParent(viewport());
        d->persistent.insert(widget);
        d->addEditor(index, widget, true);
        widget->show();
        dataChanged(index, index); // update the geometry
        if (!d->delayedPendingLayout)
            widget->setGeometry(visualRect(index));
    }
}

/*!
    \since 4.1

    Returns the widget for the item at the given \a index.
*/
QWidget* QAbstractItemView::indexWidget(const QModelIndex &index) const
{
    Q_D(const QAbstractItemView);
    if (!d->isIndexValid(index))
        return 0;
    return d->editorForIndex(index).editor;
}

/*!
    \since 4.1

    Scrolls the view to the top.

    \sa scrollTo(), scrollToBottom()
*/
void QAbstractItemView::scrollToTop()
{
    verticalScrollBar()->setValue(verticalScrollBar()->minimum());
}

/*!
    \since 4.1

    Scrolls the view to the bottom.

    \sa scrollTo(), scrollToTop()
*/
void QAbstractItemView::scrollToBottom()
{
    Q_D(QAbstractItemView);
    if (d->delayedPendingLayout) {
        d->executePostedLayout();
        updateGeometries();
    }
    verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}

/*!
    \since 4.3

    Updates the area occupied by the given \a index.

*/
void QAbstractItemView::update(const QModelIndex &index)
{
    Q_D(QAbstractItemView);
    if (index.isValid()) {
        const QRect rect = visualRect(index);
        //this test is important for peformance reason
        //For example in dataChanged we simply update all the cells without checking
        //it can be a major bottleneck to update rects that aren't even part of the viewport
        if (d->viewport->geometry().intersects(rect))
            d->viewport->update(rect);
    }
}

/*!
    This slot is called when items are changed in the model. The
    changed items are those from \a topLeft to \a bottomRight
    inclusive. If just one item is changed \a topLeft == \a
    bottomRight.
*/
void QAbstractItemView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
    // Single item changed
    Q_D(QAbstractItemView);
    if (topLeft == bottomRight && topLeft.isValid()) {
        const QEditorInfo editorInfo = d->editorForIndex(topLeft);
        //we don't update the edit data if it is static
        if (!editorInfo.isStatic && editorInfo.editor) {
            QAbstractItemDelegate *delegate = d->delegateForIndex(topLeft);
            if (delegate) {
                delegate->setEditorData(editorInfo.editor, topLeft);
            }
        }
        if (isVisible() && !d->delayedPendingLayout) {
            // otherwise the items will be update later anyway
            update(topLeft);
        }
        return;
    }
    d->updateEditorData(topLeft, bottomRight);
    if (!isVisible() || d->delayedPendingLayout)
        return; // no need to update
    d->viewport->update();
}

/*!
    This slot is called when rows are inserted. The new rows are those
    under the given \a parent from \a start to \a end inclusive. The
    base class implementation calls fetchMore() on the model to check
    for more data.

    \sa rowsAboutToBeRemoved()
*/
void QAbstractItemView::rowsInserted(const QModelIndex &, int, int)
{
    if (!isVisible())
        d_func()->fetchMoreTimer.start(0, this); //fetch more later
    else
        updateEditorGeometries();
}

/*!
    This slot is called when rows are about to be removed. The deleted rows are
    those under the given \a parent from \a start to \a end inclusive.

    \sa rowsInserted()
*/
void QAbstractItemView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
{
    Q_D(QAbstractItemView);

    setState(CollapsingState);

    // Ensure one selected item in single selection mode.
    QModelIndex current = currentIndex();
    if (d->selectionMode == SingleSelection
        && current.isValid()
        && current.row() >= start
        && current.row() <= end
        && current.parent() == parent) {
        int totalToRemove = end - start + 1;
        if (d->model->rowCount(parent) <= totalToRemove) { // no more children
            QModelIndex index = parent;
            while (index != d->root && !d->isIndexEnabled(index))
                index = index.parent();
            if (index != d->root)
                setCurrentIndex(index);
        } else {
            int row = end + 1;
            QModelIndex next;
            do { // find the next visible and enabled item
                next = d->model->index(row++, current.column(), current.parent());
            } while (next.isValid() && (isIndexHidden(next) || !d->isIndexEnabled(next)));
            if (row > d->model->rowCount(parent)) {
                row = start - 1;
                do { // find the previous visible and enabled item
                    next = d->model->index(row--, current.column(), current.parent());
                } while (next.isValid() && (isIndexHidden(next) || !d->isIndexEnabled(next)));
            }
            setCurrentIndex(next);
        }
    }

    // Remove all affected editors; this is more efficient than waiting for updateGeometries() to clean out editors for invalid indexes
    for (int i = d->editors.size() - 1; i >= 0; --i) {
        const QModelIndex index = d->editors.at(i).index;
        QWidget *editor = d->editors.at(i).editor;
        if (index.row() >= start && index.row() <= end && d->model->parent(index) == parent) {
            d->editors.removeAt(i);
            d->releaseEditor(editor);
        }
    }
}

/*!
    \internal

    This slot is called when rows have been removed. The deleted
    rows are those under the given \a parent from \a start to \a end
    inclusive.
*/
void QAbstractItemViewPrivate::_q_rowsRemoved(const QModelIndex &, int, int)
{
    Q_Q(QAbstractItemView);
    if (q->isVisible())
        q->updateEditorGeometries();
    q->setState(QAbstractItemView::NoState);
}

/*!
    \internal

    This slot is called when columns are about to be removed. The deleted
    columns are those under the given \a parent from \a start to \a end
    inclusive.
*/
void QAbstractItemViewPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
{
    Q_Q(QAbstractItemView);

    q->setState(QAbstractItemView::CollapsingState);

    // Ensure one selected item in single selection mode.
    QModelIndex current = q->currentIndex();
    if (current.isValid()
        && selectionMode == QAbstractItemView::SingleSelection
        && current.column() >= start
        && current.column() <= end) {
        int totalToRemove = end - start + 1;
        if (model->columnCount(parent) < totalToRemove) { // no more columns
            QModelIndex index = parent;
            while (index.isValid() && !isIndexEnabled(index))
                index = index.parent();
            if (index.isValid())
                q->setCurrentIndex(index);
        } else {
            int column = end;
            QModelIndex next;
            do { // find the next visible and enabled item
                next = model->index(current.row(), column++, current.parent());
            } while (next.isValid() && (q->isIndexHidden(next) || !isIndexEnabled(next)));
            q->setCurrentIndex(next);
        }
    }

    // Remove all affected editors; this is more efficient than waiting for updateGeometries() to clean out editors for invalid indexes
    QList<QEditorInfo>::iterator it = editors.begin();
    while (it != editors.end()) {
        QModelIndex index = it->index;
        if (index.column() <= start && index.column() >= end && model->parent(index) == parent) {
            QWidget *editor = it->editor;
            it = editors.erase(it);
            releaseEditor(editor);
        } else {
            ++it;
        }
    }
}

/*!
    \internal

    This slot is called when columns have been removed. The deleted
    rows are those under the given \a parent from \a start to \a end
    inclusive.
*/
void QAbstractItemViewPrivate::_q_columnsRemoved(const QModelIndex &, int, int)
{
    Q_Q(QAbstractItemView);
    if (q->isVisible())
        q->updateEditorGeometries();
    q->setState(QAbstractItemView::NoState);
}

/*!
    \internal

    This slot is called when rows have been inserted.
*/
void QAbstractItemViewPrivate::_q_columnsInserted(const QModelIndex &, int, int)
{
    Q_Q(QAbstractItemView);
    if (q->isVisible())
        q->updateEditorGeometries();
}



/*!
    \internal
*/
void QAbstractItemViewPrivate::_q_modelDestroyed()
{
    Q_Q(QAbstractItemView);
    model = QAbstractItemModelPrivate::staticEmptyModel();
    QMetaObject::invokeMethod(q, "reset", Qt::QueuedConnection);
}

/*!
    \internal

    This slot is called when the layout is changed.
*/
void QAbstractItemViewPrivate::_q_layoutChanged()
{
    doDelayedItemsLayout();
}

/*!
    This slot is called when the selection is changed. The previous
    selection (which may be empty), is specified by \a deselected, and the
    new selection by \a selected.

    \sa setSelection()
*/
void QAbstractItemView::selectionChanged(const QItemSelection &selected,
                                         const QItemSelection &deselected)
{
    Q_D(QAbstractItemView);
    if (isVisible() && updatesEnabled()) {
        d->viewport->update(visualRegionForSelection(deselected) | visualRegionForSelection(selected));
    }
}

/*!
    This slot is called when a new item becomes the current item.
    The previous current item is specified by the \a previous index, and the new
    item by the \a current index.

    If you want to know about changes to items see the
    dataChanged() signal.
*/
void QAbstractItemView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    Q_D(QAbstractItemView);
    Q_ASSERT(d->model);

    if (previous.isValid()) {
        QModelIndex buddy = d->model->buddy(previous);
        QWidget *editor = d->editorForIndex(buddy).editor;
        if (editor && !d->persistent.contains(editor)) {
            commitData(editor);
            if (current.row() != previous.row())
                closeEditor(editor, QAbstractItemDelegate::SubmitModelCache);
            else
                closeEditor(editor, QAbstractItemDelegate::NoHint);
        }
        if (isVisible()) {
            update(previous);
        }
    }

    if (current.isValid() && !d->autoScrollTimer.isActive()) {
        if (isVisible()) {
            if (d->autoScroll)
                scrollTo(current);
            update(current);
            edit(current, CurrentChanged, 0);
            if (current.row() == (d->model->rowCount(d->root) - 1))
                d->fetchMore();
        } else {
            d->shouldScrollToCurrentOnShow = d->autoScroll;
        }
    }
}

#ifndef QT_NO_DRAGANDDROP
/*!
    Starts a drag by calling drag->exec() using the given \a supportedActions.
*/
void QAbstractItemView::startDrag(Qt::DropActions supportedActions)
{
    Q_D(QAbstractItemView);
    QModelIndexList indexes = d->selectedDraggableIndexes();
    if (indexes.count() > 0) {
        QMimeData *data = d->model->mimeData(indexes);
        if (!data)
            return;
        QRect rect;
        QPixmap pixmap = d->renderToPixmap(indexes, &rect);
        rect.adjust(horizontalOffset(), verticalOffset(), 0, 0);
        QDrag *drag = new QDrag(this);
        drag->setPixmap(pixmap);
        drag->setMimeData(data);
        drag->setHotSpot(d->pressedPosition - rect.topLeft());
        Qt::DropAction defaultDropAction = Qt::IgnoreAction;
        if (supportedActions & Qt::CopyAction && dragDropMode() != QAbstractItemView::InternalMove)
            defaultDropAction = Qt::CopyAction;
        if (drag->exec(supportedActions, defaultDropAction) == Qt::MoveAction)
            d->clearOrRemove();
    }
}
#endif // QT_NO_DRAGANDDROP

/*!
    Returns a QStyleOptionViewItem structure populated with the view's
    palette, font, state, alignments etc.
*/
QStyleOptionViewItem QAbstractItemView::viewOptions() const
{
    Q_D(const QAbstractItemView);
    QStyleOptionViewItem option;
    option.init(this);
    option.state &= ~QStyle::State_MouseOver;
    option.font = font();

#ifndef Q_WS_MAC
    // On mac the focus appearance follows window activation
    // not widget activation
    if (!hasFocus())
        option.state &= ~QStyle::State_Active;
#endif

    option.state &= ~QStyle::State_HasFocus;
    if (d->iconSize.isValid()) {
        option.decorationSize = d->iconSize;
    } else {
        int pm = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, this);
        option.decorationSize = QSize(pm, pm);
    }
    option.decorationPosition = QStyleOptionViewItem::Left;
    option.decorationAlignment = Qt::AlignCenter;
    option.displayAlignment = Qt::AlignLeft|Qt::AlignVCenter;
    option.textElideMode = d->textElideMode;
    option.rect = QRect();
    option.showDecorationSelected = style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, 0, this);
    return option;
}

QStyleOptionViewItemV4 QAbstractItemViewPrivate::viewOptionsV4() const
{
    Q_Q(const QAbstractItemView);
    QStyleOptionViewItemV4 option = q->viewOptions();
    if (wrapItemText)
        option.features = QStyleOptionViewItemV2::WrapText;
    option.locale = q->locale();
    option.locale.setNumberOptions(QLocale::OmitGroupSeparator);
    option.widget = q;
    return option;
}

/*!
    Returns the item view's state.

    \sa setState()
*/
QAbstractItemView::State QAbstractItemView::state() const
{
    Q_D(const QAbstractItemView);
    return d->state;
}

/*!
    Sets the item view's state to the given \a state.

    \sa state()
*/
void QAbstractItemView::setState(State state)
{
    Q_D(QAbstractItemView);
    d->state = state;
}

/*!
  Schedules a layout of the items in the view to be executed when the
  event processing starts.

  Even if scheduleDelayedItemsLayout() is called multiple times before
  events are processed, the view will only do the layout once.

  \sa executeDelayedItemsLayout()
*/
void QAbstractItemView::scheduleDelayedItemsLayout()
{
    Q_D(QAbstractItemView);
    d->doDelayedItemsLayout();
}

/*!
  Executes the scheduled layouts without waiting for the event processing
  to begin.

  \sa scheduleDelayedItemsLayout()
*/
void QAbstractItemView::executeDelayedItemsLayout()
{
    Q_D(QAbstractItemView);
    d->executePostedLayout();
}

/*!
    \since 4.1

    Marks the given \a region as dirty and schedules it to be updated.
    You only need to call this function if you are implementing
    your own view subclass.

    \sa scrollDirtyRegion(), dirtyRegionOffset()
*/

void QAbstractItemView::setDirtyRegion(const QRegion &region)
{
    Q_D(QAbstractItemView);
    d->setDirtyRegion(region);
}

/*!
  Prepares the view for scrolling by (\a{dx},\a{dy}) pixels by moving the dirty regions in the
  opposite direction. You only need to call this function if you are implementing a scrolling
  viewport in your view subclass.

  If you implement scrollContentsBy() in a subclass of QAbstractItemView, call this function
  before you call QWidget::scroll() on the viewport. Alternatively, just call update().

  \sa scrollContentsBy(), dirtyRegionOffset(), setDirtyRegion()
*/
void QAbstractItemView::scrollDirtyRegion(int dx, int dy)
{
    Q_D(QAbstractItemView);
    d->scrollDirtyRegion(dx, dy);
}

/*!
  Returns the offset of the dirty regions in the view.

  If you use scrollDirtyRegion() and implement a paintEvent() in a subclass of
  QAbstractItemView, you should translate the area given by the paint event with
  the offset returned from this function.

  \sa scrollDirtyRegion(), setDirtyRegion()
*/
QPoint QAbstractItemView::dirtyRegionOffset() const
{
    Q_D(const QAbstractItemView);
    return d->scrollDelayOffset;
}

/*!
  \internal
*/
void QAbstractItemView::startAutoScroll()
{
    Q_D(QAbstractItemView);
    // ### it would be nice to make this into a style hint one day
    int scrollInterval = (verticalScrollMode() == QAbstractItemView::ScrollPerItem) ? 150 : 50;
    d->autoScrollTimer.start(scrollInterval, this);
    d->autoScrollCount = 0;
}

/*!
  \internal
*/
void QAbstractItemView::stopAutoScroll()
{
    Q_D(QAbstractItemView);
    d->autoScrollTimer.stop();
    d->autoScrollCount = 0;
}

/*!
  \internal
*/
void QAbstractItemView::doAutoScroll()
{
    // find how much we should scroll with
    Q_D(QAbstractItemView);
    int verticalStep = verticalScrollBar()->pageStep();
    int horizontalStep = horizontalScrollBar()->pageStep();
    if (d->autoScrollCount < qMax(verticalStep, horizontalStep))
        ++d->autoScrollCount;

    int margin = d->autoScrollMargin;
    int verticalValue = verticalScrollBar()->value();
    int horizontalValue = horizontalScrollBar()->value();

    QPoint pos = d->viewport->mapFromGlobal(QCursor::pos());
    QRect area = static_cast<QAbstractItemView*>(d->viewport)->d_func()->clipRect(); // access QWidget private by bending C++ rules

    // do the scrolling if we are in the scroll margins
    if (pos.y() - area.top() < margin)
        verticalScrollBar()->setValue(verticalValue - d->autoScrollCount);
    else if (area.bottom() - pos.y() < margin)
        verticalScrollBar()->setValue(verticalValue + d->autoScrollCount);
    if (pos.x() - area.left() < margin)
        horizontalScrollBar()->setValue(horizontalValue - d->autoScrollCount);
    else if (area.right() - pos.x() < margin)
        horizontalScrollBar()->setValue(horizontalValue + d->autoScrollCount);
    // if nothing changed, stop scrolling
    bool verticalUnchanged = (verticalValue == verticalScrollBar()->value());
    bool horizontalUnchanged = (horizontalValue == horizontalScrollBar()->value());
    if (verticalUnchanged && horizontalUnchanged) {
        stopAutoScroll();
    } else {
#ifndef QT_NO_DRAGANDDROP
        d->dropIndicatorRect = QRect();
        d->dropIndicatorPosition = QAbstractItemView::OnViewport;
#endif
        d->viewport->update();
    }
}

/*!
    Returns the SelectionFlags to be used when updating a selection with
    to include the \a index specified. The \a event is a user input event,
    such as a mouse or keyboard event.

    Reimplement this function to define your own selection behavior.

    \sa setSelection()
*/
QItemSelectionModel::SelectionFlags QAbstractItemView::selectionCommand(const QModelIndex &index,
                                                                        const QEvent *event) const
{
    Q_D(const QAbstractItemView);
    switch (d->selectionMode) {
        case NoSelection: // Never update selection model
            return QItemSelectionModel::NoUpdate;
        case SingleSelection: // ClearAndSelect on valid index otherwise NoUpdate
            if (event && event->type() == QEvent::MouseButtonRelease)
                return QItemSelectionModel::NoUpdate;
            return QItemSelectionModel::ClearAndSelect|d->selectionBehaviorFlags();
        case MultiSelection:
            return d->multiSelectionCommand(index, event);
        case ExtendedSelection:
            return d->extendedSelectionCommand(index, event);
        case ContiguousSelection:
            return d->contiguousSelectionCommand(index, event);
    }
    return QItemSelectionModel::NoUpdate;
}

QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::multiSelectionCommand(
    const QModelIndex &index, const QEvent *event) const
{
    Q_UNUSED(index);

    if (event) {
        switch (event->type()) {
        case QEvent::KeyPress:
            if (static_cast<const QKeyEvent*>(event)->key() == Qt::Key_Space
             || static_cast<const QKeyEvent*>(event)->key() == Qt::Key_Select)
                return QItemSelectionModel::Toggle|selectionBehaviorFlags();
            break;
        case QEvent::MouseButtonPress:
            if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton)
                return QItemSelectionModel::Toggle|selectionBehaviorFlags(); // toggle
            break;
        case QEvent::MouseButtonRelease:
            if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton)
                return QItemSelectionModel::NoUpdate|selectionBehaviorFlags(); // finalize
            break;
        case QEvent::MouseMove:
            if (static_cast<const QMouseEvent*>(event)->buttons() & Qt::LeftButton)
                return QItemSelectionModel::ToggleCurrent|selectionBehaviorFlags(); // toggle drag select
        default:
            break;
        }
        return QItemSelectionModel::NoUpdate;
    }

    return QItemSelectionModel::Toggle|selectionBehaviorFlags();
}

QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionCommand(
    const QModelIndex &index, const QEvent *event) const
{
    Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers();
    if (event) {
        switch (event->type()) {
        case QEvent::MouseMove: {
            // Toggle on MouseMove
            modifiers = static_cast<const QMouseEvent*>(event)->modifiers();
            if (modifiers & Qt::ControlModifier)
                return QItemSelectionModel::ToggleCurrent|selectionBehaviorFlags();
            break;
        }
        case QEvent::MouseButtonPress: {
            modifiers = static_cast<const QMouseEvent*>(event)->modifiers();
            const Qt::MouseButton button = static_cast<const QMouseEvent*>(event)->button();
            const bool rightButtonPressed = button & Qt::RightButton;
            const bool shiftKeyPressed = modifiers & Qt::ShiftModifier;
            const bool controlKeyPressed = modifiers & Qt::ControlModifier;
            const bool indexIsSelected = selectionModel->isSelected(index);
            if ((shiftKeyPressed || controlKeyPressed) && rightButtonPressed)
                return QItemSelectionModel::NoUpdate;
            if (!shiftKeyPressed && !controlKeyPressed && indexIsSelected)
                return QItemSelectionModel::NoUpdate;
            if (!index.isValid() && !rightButtonPressed && !shiftKeyPressed && !controlKeyPressed)
                return QItemSelectionModel::Clear;
            if (!index.isValid())
                return QItemSelectionModel::NoUpdate;
            break;
        }
        case QEvent::MouseButtonRelease: {
            // ClearAndSelect on MouseButtonRelease if MouseButtonPress on selected item or empty area
            modifiers = static_cast<const QMouseEvent*>(event)->modifiers();
            const Qt::MouseButton button = static_cast<const QMouseEvent*>(event)->button();
            const bool rightButtonPressed = button & Qt::RightButton;
            const bool shiftKeyPressed = modifiers & Qt::ShiftModifier;
            const bool controlKeyPressed = modifiers & Qt::ControlModifier;
            if (((index == pressedIndex && selectionModel->isSelected(index))
		 || !index.isValid()) && state != QAbstractItemView::DragSelectingState
                && !shiftKeyPressed && !controlKeyPressed && !rightButtonPressed)
                return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
            return QItemSelectionModel::NoUpdate;
        }
        case QEvent::KeyPress: {
            // NoUpdate on Key movement and Ctrl
            modifiers = static_cast<const QKeyEvent*>(event)->modifiers();
            switch (static_cast<const QKeyEvent*>(event)->key()) {
            case Qt::Key_Backtab:
                modifiers = modifiers & ~Qt::ShiftModifier; // special case for backtab
            case Qt::Key_Down:
            case Qt::Key_Up:
            case Qt::Key_Left:
            case Qt::Key_Right:
            case Qt::Key_Home:
            case Qt::Key_End:
            case Qt::Key_PageUp:
            case Qt::Key_PageDown:
            case Qt::Key_Tab:
#ifdef QT_KEYPAD_NAVIGATION
                return QItemSelectionModel::NoUpdate;
#else
                if (modifiers & Qt::ControlModifier)
                    return QItemSelectionModel::NoUpdate;
#endif
                break;
            case Qt::Key_Select:
                return QItemSelectionModel::Toggle|selectionBehaviorFlags();
            case Qt::Key_Space:// Toggle on Ctrl-Qt::Key_Space, Select on Space
                if (modifiers & Qt::ControlModifier)
                    return QItemSelectionModel::Toggle|selectionBehaviorFlags();
                return QItemSelectionModel::Select|selectionBehaviorFlags();
            default:
                break;
            }
        }
        default:
            break;
        }
    }

    if (modifiers & Qt::ShiftModifier)
        return QItemSelectionModel::SelectCurrent|selectionBehaviorFlags();
    if (modifiers & Qt::ControlModifier)
        return QItemSelectionModel::Toggle|selectionBehaviorFlags();
    if (state == QAbstractItemView::DragSelectingState) {
        //when drag-selecting we need to clear any previous selection and select the current one
        return QItemSelectionModel::Clear|QItemSelectionModel::SelectCurrent|selectionBehaviorFlags();
    }

    return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
}

QItemSelectionModel::SelectionFlags
QAbstractItemViewPrivate::contiguousSelectionCommand(const QModelIndex &index,
                                                     const QEvent *event) const
{
    QItemSelectionModel::SelectionFlags flags = extendedSelectionCommand(index, event);
    const int Mask = QItemSelectionModel::Clear | QItemSelectionModel::Select
                     | QItemSelectionModel::Deselect | QItemSelectionModel::Toggle
                     | QItemSelectionModel::Current;

    switch (flags & Mask) {
    case QItemSelectionModel::Clear:
    case QItemSelectionModel::ClearAndSelect:
    case QItemSelectionModel::SelectCurrent:
        return flags;
    case QItemSelectionModel::NoUpdate:
        if (event &&
            (event->type() == QEvent::MouseButtonPress
             || event->type() == QEvent::MouseButtonRelease))
            return flags;
        return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
    default:
        return QItemSelectionModel::SelectCurrent|selectionBehaviorFlags();
    }
}

void QAbstractItemViewPrivate::fetchMore()
{
    fetchMoreTimer.stop();
    if (!model->canFetchMore(root))
        return;
    int last = model->rowCount(root) - 1;
    if (last < 0) {
        model->fetchMore(root);
        return;
    }

    QModelIndex index = model->index(last, 0, root);
    QRect rect = q_func()->visualRect(index);
    if (viewport->rect().intersects(rect))
        model->fetchMore(root);
}

bool QAbstractItemViewPrivate::shouldEdit(QAbstractItemView::EditTrigger trigger,
                                          const QModelIndex &index) const
{
    if (!index.isValid())
        return false;
    Qt::ItemFlags flags = model->flags(index);
    if (((flags & Qt::ItemIsEditable) == 0) || ((flags & Qt::ItemIsEnabled) == 0))
        return false;
    if (state == QAbstractItemView::EditingState)
        return false;
    if (hasEditor(index))
        return false;
    if (trigger == QAbstractItemView::AllEditTriggers) // force editing
        return true;
    if ((trigger & editTriggers) == QAbstractItemView::SelectedClicked
        && !selectionModel->isSelected(index))
        return false;
    return (trigger & editTriggers);
}

bool QAbstractItemViewPrivate::shouldForwardEvent(QAbstractItemView::EditTrigger trigger,
                                                  const QEvent *event) const
{
    if (!event || (trigger & editTriggers) != QAbstractItemView::AnyKeyPressed)
        return false;

    switch (event->type()) {
        case QEvent::KeyPress:
        case QEvent::MouseButtonDblClick:
        case QEvent::MouseButtonPress:
        case QEvent::MouseButtonRelease:
        case QEvent::MouseMove:
            return true;
        default:
            break;
    };

    return false;
}

bool QAbstractItemViewPrivate::shouldAutoScroll(const QPoint &pos) const
{
    if (!autoScroll)
        return false;
    QRect area = static_cast<QAbstractItemView*>(viewport)->d_func()->clipRect(); // access QWidget private by bending C++ rules
    return (pos.y() - area.top() < autoScrollMargin)
        || (area.bottom() - pos.y() < autoScrollMargin)
        || (pos.x() - area.left() < autoScrollMargin)
        || (area.right() - pos.x() < autoScrollMargin);
}

void QAbstractItemViewPrivate::doDelayedItemsLayout(int delay)
{
    if (!delayedPendingLayout) {
        delayedPendingLayout = true;
        delayedLayout.start(delay, q_func());
    }
}

void QAbstractItemViewPrivate::interruptDelayedItemsLayout() const
{
    delayedLayout.stop();
    delayedPendingLayout = false;
}



QWidget *QAbstractItemViewPrivate::editor(const QModelIndex &index,
                                          const QStyleOptionViewItem &options)
{
    Q_Q(QAbstractItemView);
    QWidget *w = editorForIndex(index).editor;
    if (!w) {
        QAbstractItemDelegate *delegate = delegateForIndex(index);
        if (!delegate)
            return 0;
        w = delegate->createEditor(viewport, options, index);
        if (w) {
            w->installEventFilter(delegate);
            QObject::connect(w, SIGNAL(destroyed(QObject*)), q, SLOT(editorDestroyed(QObject*)));
            delegate->updateEditorGeometry(w, options, index);
            delegate->setEditorData(w, index);
            addEditor(index, w, false);
            if (w->parent() == viewport)
                QWidget::setTabOrder(q, w);

            // Special cases for some editors containing QLineEdit
            QWidget *focusWidget = w;
            while (QWidget *fp = focusWidget->focusProxy())
                focusWidget = fp;
#ifndef QT_NO_LINEEDIT
            if (QLineEdit *le = qobject_cast<QLineEdit*>(focusWidget))
                le->selectAll();
#endif
#ifndef QT_NO_SPINBOX
            if (QSpinBox *sb = qobject_cast<QSpinBox*>(focusWidget))
                sb->selectAll();
            else if (QDoubleSpinBox *dsb = qobject_cast<QDoubleSpinBox*>(focusWidget))
                dsb->selectAll();
#endif
        }
    }
    return w;
}

void QAbstractItemViewPrivate::updateEditorData(const QModelIndex &tl, const QModelIndex &br)
{
    // we are counting on having relatively few editors
    const bool checkIndexes = tl.isValid() && br.isValid();
    const QModelIndex parent = tl.parent();
    QList<QEditorInfo>::const_iterator it = editors.constBegin();
    for (; it != editors.constEnd(); ++it) {
        QWidget *editor = it->editor;
        const QModelIndex index = it->index;
        if (it->isStatic || editor == 0 || !index.isValid() ||
            (checkIndexes
                && (index.row() < tl.row() || index.row() > br.row()
                    || index.column() < tl.column() || index.column() > br.column()
                    || index.parent() != parent)))
            continue;

        QAbstractItemDelegate *delegate = delegateForIndex(index);
        if (delegate) {
            delegate->setEditorData(editor, index);
        }
    }
}

/*!
    \internal

    In DND if something has been moved then this is called.
    Typically this means you should "remove" the selected item or row,
    but the behavior is view dependant (table just clears the selected indexes for example).

    Either remove the selected rows or clear them
  */
void QAbstractItemViewPrivate::clearOrRemove()
{
#ifndef QT_NO_DRAGANDDROP
    const QItemSelection selection = selectionModel->selection();
    QList<QItemSelectionRange>::const_iterator it = selection.constBegin();

    if (!overwrite) {
        for (; it != selection.constEnd(); ++it) {
            QModelIndex parent = (*it).parent();
            if ((*it).left() != 0)
                continue;
            if ((*it).right() != (model->columnCount(parent) - 1))
                continue;
            int count = (*it).bottom() - (*it).top() + 1;
            model->removeRows((*it).top(), count, parent);
        }
    } else {
        // we can't remove the rows so reset the items (i.e. the view is like a table)
        QModelIndexList list = selection.indexes();
        for (int i=0; i < list.size(); ++i) {
            QModelIndex index = list.at(i);
            QMap<int, QVariant> roles = model->itemData(index);
            for (QMap<int, QVariant>::Iterator it = roles.begin(); it != roles.end(); ++it)
                it.value() = QVariant();
            model->setItemData(index, roles);
        }
    }
#endif
}

/*!
    \internal

    When persistent aeditor gets/loses focus, we need to check
    and setcorrectly the current index.
  */
void QAbstractItemViewPrivate::checkPersistentEditorFocus()
{
    Q_Q(QAbstractItemView);
    if (QWidget *widget = QApplication::focusWidget()) {
        if (persistent.contains(widget)) {
            //a persistent editor has gained the focus
            QModelIndex index = indexForEditor(widget);
            if (selectionModel->currentIndex() != index)
                q->setCurrentIndex(index);
        }
    }
}


QEditorInfo QAbstractItemViewPrivate::editorForIndex(const QModelIndex &index) const
{
    QList<QEditorInfo>::const_iterator it = editors.constBegin();
    for (; it != editors.constEnd(); ++it) {
        if (it->index == index)
            return *it;
    }

    return QEditorInfo();
}

QModelIndex QAbstractItemViewPrivate::indexForEditor(QWidget *editor) const
{
    QList<QEditorInfo>::const_iterator it = editors.constBegin();
    for (; it != editors.constEnd(); ++it) {
        if (it->editor == editor)
            return it->index;
    }
    return QModelIndex();
}

void QAbstractItemViewPrivate::removeEditor(QWidget *editor)
{
    QList<QEditorInfo>::iterator it = editors.begin();
    for (; it != editors.end(); ) {
        if (it->editor == editor)
            it = editors.erase(it);
        else
            ++it;
    }
}

void QAbstractItemViewPrivate::addEditor(const QModelIndex &index, QWidget *editor, bool isStatic)
{
    editors.append(QEditorInfo(index, editor, isStatic));
}

bool QAbstractItemViewPrivate::sendDelegateEvent(const QModelIndex &index, QEvent *event) const
{
    Q_Q(const QAbstractItemView);
    QModelIndex buddy = model->buddy(index);
    QStyleOptionViewItemV4 options = viewOptionsV4();
    options.rect = q->visualRect(buddy);
    options.state |= (buddy == q->currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
    QAbstractItemDelegate *delegate = delegateForIndex(index);
    return (event && delegate && delegate->editorEvent(event, model, options, buddy));
}

bool QAbstractItemViewPrivate::openEditor(const QModelIndex &index, QEvent *event)
{
    Q_Q(QAbstractItemView);

    QModelIndex buddy = model->buddy(index);
    QStyleOptionViewItemV4 options = viewOptionsV4();
    options.rect = q->visualRect(buddy);
    options.state |= (buddy == q->currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);

    QWidget *w = editor(buddy, options);
    if (!w)
        return false;

    if (event)
        QApplication::sendEvent(w->focusProxy() ? w->focusProxy() : w, event);

    q->setState(QAbstractItemView::EditingState);
    w->show();
    w->setFocus();

    return true;
}

/*
  \internal

  returns the pair QRect/QModelIndex that should be painted on the viewports's rect
  */

QItemViewPaintPairs QAbstractItemViewPrivate::draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const
{
    Q_ASSERT(r);
    Q_Q(const QAbstractItemView);
    QRect &rect = *r;
    const QRect viewportRect = viewport->rect();
    QItemViewPaintPairs ret;
    for (int i = 0; i < indexes.count(); ++i) {
        const QModelIndex &index = indexes.at(i);
        const QRect current = q->visualRect(index);
        if (current.intersects(viewportRect)) {
            ret += qMakePair(current, index);
            rect |= current;
        }
    }
    rect &= viewportRect;
    return ret;
}

QPixmap QAbstractItemViewPrivate::renderToPixmap(const QModelIndexList &indexes, QRect *r) const
{
    Q_ASSERT(r);
    QItemViewPaintPairs paintPairs = draggablePaintPairs(indexes, r);
    if (paintPairs.isEmpty())
        return QPixmap();
    QPixmap pixmap(r->size());
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    QStyleOptionViewItemV4 option = viewOptionsV4();
    option.state |= QStyle::State_Selected;
    for (int j = 0; j < paintPairs.count(); ++j) {
        option.rect = paintPairs.at(j).first.translated(-r->topLeft());
        const QModelIndex &current = paintPairs.at(j).second;
        delegateForIndex(current)->paint(&painter, option, current);
    }
    return pixmap;
}

void QAbstractItemViewPrivate::selectAll(QItemSelectionModel::SelectionFlags command)
{
    if (!selectionModel)
        return;

    QItemSelection selection;
    QModelIndex tl = model->index(0, 0, root);
    QModelIndex br = model->index(model->rowCount(root) - 1,
                                  model->columnCount(root) - 1,
                                  root);
    selection.append(QItemSelectionRange(tl, br));
    selectionModel->select(selection, command);
}

QModelIndexList QAbstractItemViewPrivate::selectedDraggableIndexes() const
{
    Q_Q(const QAbstractItemView);
    QModelIndexList indexes = q->selectedIndexes();
    for(int i = indexes.count() - 1 ; i >= 0; --i) {
        if (!isIndexDragEnabled(indexes.at(i)))
            indexes.removeAt(i);
    }
    return indexes;
}


QT_END_NAMESPACE

#include "moc_qabstractitemview.cpp"

#endif // QT_NO_ITEMVIEWS