summaryrefslogtreecommitdiffstats
path: root/src/widgets/itemviews/qheaderview.cpp
blob: 4c5d17ba6992e60652b3950e664e431d52f8dad2 (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
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qheaderview.h"

#include <qbitarray.h>
#include <qbrush.h>
#include <qdebug.h>
#include <qevent.h>
#include <qpainter.h>
#include <qscrollbar.h>
#include <qtooltip.h>
#if QT_CONFIG(whatsthis)
#include <qwhatsthis.h>
#endif
#include <qstyle.h>
#include <qstyleoption.h>
#include <qvector.h>
#include <qapplication.h>
#include <qvarlengtharray.h>
#include <qabstractitemdelegate.h>
#include <qvariant.h>
#include <private/qheaderview_p.h>
#include <private/qabstractitemmodel_p.h>

#ifndef QT_NO_DATASTREAM
#include <qdatastream.h>
#endif

QT_BEGIN_NAMESPACE

#ifndef QT_NO_DATASTREAM
QDataStream &operator<<(QDataStream &out, const QHeaderViewPrivate::SectionItem &section)
{
    section.write(out);
    return out;
}

QDataStream &operator>>(QDataStream &in, QHeaderViewPrivate::SectionItem &section)
{
    section.read(in);
    return in;
}
#endif // QT_NO_DATASTREAM

static const int maxSizeSection = 1048575; // since section size is in a bitfield (uint 20). See qheaderview_p.h
                                           // if this is changed then the docs in maximumSectionSize should be changed.

/*!
    \class QHeaderView

    \brief The QHeaderView class provides a header row or header column for
    item views.

    \ingroup model-view
    \inmodule QtWidgets

    A QHeaderView displays the headers used in item views such as the
    QTableView and QTreeView classes. It takes the place of Qt3's \c QHeader
    class previously used for the same purpose, but uses the Qt's model/view
    architecture for consistency with the item view classes.

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

    The header gets the data for each section from the model using the
    QAbstractItemModel::headerData() function. You can set the data by using
    QAbstractItemModel::setHeaderData().

    Each header has an orientation() and a number of sections, given by the
    count() function. A section refers to a part of the header - either a row
    or a column, depending on the orientation.

    Sections can be moved and resized using moveSection() and resizeSection();
    they can also be hidden and shown with hideSection() and showSection().

    Each section of a header is described by a section ID, specified by its
    section(), and can be located at a particular visualIndex() in the header.
    A section can have a sort indicator set with setSortIndicator(); this
    indicates whether the items in the associated item view will be sorted in
    the order given by the section.

    For a horizontal header the section is equivalent to a column in the model,
    and for a vertical header the section is equivalent to a row in the model.

    \section1 Moving Header Sections

    A header can be fixed in place, or made movable with setSectionsMovable(). It can
    be made clickable with setSectionsClickable(), and has resizing behavior in
    accordance with setSectionResizeMode().

    \note Double-clicking on a header to resize a section only applies for
    visible rows.

    A header will emit sectionMoved() if the user moves a section,
    sectionResized() if the user resizes a section, and sectionClicked() as
    well as sectionHandleDoubleClicked() in response to mouse clicks. A header
    will also emit sectionCountChanged().

    You can identify a section using the logicalIndex() and logicalIndexAt()
    functions, or by its index position, using the visualIndex() and
    visualIndexAt() functions. The visual index will change if a section is
    moved, but the logical index will not change.

    \section1 Appearance

    QTableWidget and QTableView create default headers. If you want
    the headers to be visible, you can use \l{QFrame::}{setVisible()}.

    Not all \l{Qt::}{ItemDataRole}s will have an effect on a
    QHeaderView. If you need to draw other roles, you can subclass
    QHeaderView and reimplement \l{QHeaderView::}{paintEvent()}.
    QHeaderView respects the following item data roles:
    \l{Qt::}{TextAlignmentRole}, \l{Qt::}{DisplayRole},
    \l{Qt::}{FontRole}, \l{Qt::}{DecorationRole},
    \l{Qt::}{ForegroundRole}, and \l{Qt::}{BackgroundRole}.

    \note Each header renders the data for each section itself, and does not
    rely on a delegate. As a result, calling a header's setItemDelegate()
    function will have no effect.

    \sa {Model/View Programming}, QListView, QTableView, QTreeView
*/

/*!
    \enum QHeaderView::ResizeMode

    The resize mode specifies the behavior of the header sections. It can be
    set on the entire header view or on individual sections using
    setSectionResizeMode().

    \value Interactive The user can resize the section. The section can also be
           resized programmatically using resizeSection().  The section size
           defaults to \l defaultSectionSize. (See also
           \l cascadingSectionResizes.)

    \value Fixed The user cannot resize the section. The section can only be
           resized programmatically using resizeSection(). The section size
           defaults to \l defaultSectionSize.

    \value Stretch QHeaderView will automatically resize the section to fill
           the available space. The size cannot be changed by the user or
           programmatically.

    \value ResizeToContents QHeaderView will automatically resize the section
           to its optimal size based on the contents of the entire column or
           row. The size cannot be changed by the user or programmatically.
           (This value was introduced in 4.2)

    The following values are obsolete:
    \value Custom Use Fixed instead.

    \sa setResizeMode(), setSectionResizeMode(), stretchLastSection, minimumSectionSize
*/

/*!
    \fn void QHeaderView::sectionMoved(int logicalIndex, int oldVisualIndex,
    int newVisualIndex)

    This signal is emitted when a section is moved. The section's logical index
    is specified by \a logicalIndex, the old index by \a oldVisualIndex, and
    the new index position by \a newVisualIndex.

    \sa moveSection()
*/

/*!
    \fn void QHeaderView::sectionResized(int logicalIndex, int oldSize,
    int newSize)

    This signal is emitted when a section is resized. The section's logical
    number is specified by \a logicalIndex, the old size by \a oldSize, and the
    new size by \a newSize.

    \sa resizeSection()
*/

/*!
    \fn void QHeaderView::sectionPressed(int logicalIndex)

    This signal is emitted when a section is pressed. The section's logical
    index is specified by \a logicalIndex.

    \sa setSectionsClickable()
*/

/*!
    \fn void QHeaderView::sectionClicked(int logicalIndex)

    This signal is emitted when a section is clicked. The section's logical
    index is specified by \a logicalIndex.

    Note that the sectionPressed signal will also be emitted.

    \sa setSectionsClickable(), sectionPressed()
*/

/*!
    \fn void QHeaderView::sectionEntered(int logicalIndex)
    \since 4.3

    This signal is emitted when the cursor moves over the section and the left
    mouse button is pressed. The section's logical index is specified by
    \a logicalIndex.

    \sa setSectionsClickable(), sectionPressed()
*/

/*!
    \fn void QHeaderView::sectionDoubleClicked(int logicalIndex)

    This signal is emitted when a section is double-clicked. The section's
    logical index is specified by \a logicalIndex.

    \sa setSectionsClickable()
*/

/*!
    \fn void QHeaderView::sectionCountChanged(int oldCount, int newCount)

    This signal is emitted when the number of sections changes, i.e., when
    sections are added or deleted. The original count is specified by
    \a oldCount, and the new count by \a newCount.

    \sa count(), length(), headerDataChanged()
*/

/*!
    \fn void QHeaderView::sectionHandleDoubleClicked(int logicalIndex)

    This signal is emitted when a section is double-clicked. The section's
    logical index is specified by \a logicalIndex.

    \sa setSectionsClickable()
*/

/*!
    \fn void QHeaderView::sortIndicatorChanged(int logicalIndex,
    Qt::SortOrder order)
    \since 4.3

    This signal is emitted when the section containing the sort indicator or
    the order indicated is changed. The section's logical index is specified
    by \a logicalIndex and the sort order is specified by \a order.

    \sa setSortIndicator()
*/

/*!
    \fn void QHeaderView::geometriesChanged()
    \since 4.2

    This signal is emitted when the header's geometries have changed.
*/

/*!
    \property QHeaderView::highlightSections
    \brief whether the sections containing selected items are highlighted

    By default, this property is \c false.
*/

/*!
    Creates a new generic header with the given \a orientation and \a parent.
*/
QHeaderView::QHeaderView(Qt::Orientation orientation, QWidget *parent)
    : QAbstractItemView(*new QHeaderViewPrivate, parent)
{
    Q_D(QHeaderView);
    d->setDefaultValues(orientation);
    initialize();
}

/*!
  \internal
*/
QHeaderView::QHeaderView(QHeaderViewPrivate &dd,
                         Qt::Orientation orientation, QWidget *parent)
    : QAbstractItemView(dd, parent)
{
    Q_D(QHeaderView);
    d->setDefaultValues(orientation);
    initialize();
}

/*!
  Destroys the header.
*/

QHeaderView::~QHeaderView()
{
}

/*!
  \internal
*/
void QHeaderView::initialize()
{
    Q_D(QHeaderView);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setFrameStyle(NoFrame);
    setFocusPolicy(Qt::NoFocus);
    d->viewport->setMouseTracking(true);
    d->viewport->setBackgroundRole(QPalette::Button);
    d->textElideMode = Qt::ElideNone;
    delete d->itemDelegate;
}

/*!
  \reimp
*/
void QHeaderView::setModel(QAbstractItemModel *model)
{
    if (model == this->model())
        return;
    Q_D(QHeaderView);
    d->persistentHiddenSections.clear();
    if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
    if (d->orientation == Qt::Horizontal) {
        QObject::disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
                            this, SLOT(sectionsInserted(QModelIndex,int,int)));
        QObject::disconnect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
                            this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
        QObject::disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
                            this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
        QObject::disconnect(d->model, SIGNAL(columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)),
                            this, SLOT(_q_sectionsAboutToBeChanged()));
        QObject::disconnect(d->model, SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)),
                            this, SLOT(_q_sectionsChanged()));
    } else {
        QObject::disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
                            this, SLOT(sectionsInserted(QModelIndex,int,int)));
        QObject::disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
                            this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
        QObject::disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
                            this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
        QObject::disconnect(d->model, SIGNAL(rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)),
                            this, SLOT(_q_sectionsAboutToBeChanged()));
        QObject::disconnect(d->model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
                            this, SLOT(_q_sectionsChanged()));
    }
    QObject::disconnect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
                        this, SLOT(headerDataChanged(Qt::Orientation,int,int)));
    QObject::disconnect(d->model, SIGNAL(layoutAboutToBeChanged()),
                        this, SLOT(_q_sectionsAboutToBeChanged()));
    QObject::disconnect(d->model, SIGNAL(layoutChanged()),
                        this, SLOT(_q_sectionsChanged()));
    }

    if (model && model != QAbstractItemModelPrivate::staticEmptyModel()) {
        if (d->orientation == Qt::Horizontal) {
            QObject::connect(model, SIGNAL(columnsInserted(QModelIndex,int,int)),
                             this, SLOT(sectionsInserted(QModelIndex,int,int)));
            QObject::connect(model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
                             this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
            QObject::connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
                             this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
            QObject::connect(model, SIGNAL(columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)),
                             this, SLOT(_q_sectionsAboutToBeChanged()));
            QObject::connect(model, SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)),
                             this, SLOT(_q_sectionsChanged()));
        } else {
            QObject::connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
                             this, SLOT(sectionsInserted(QModelIndex,int,int)));
            QObject::connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
                             this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
            QObject::connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
                             this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
            QObject::connect(model, SIGNAL(rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)),
                             this, SLOT(_q_sectionsAboutToBeChanged()));
            QObject::connect(model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
                             this, SLOT(_q_sectionsChanged()));
        }
        QObject::connect(model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
                         this, SLOT(headerDataChanged(Qt::Orientation,int,int)));
        QObject::connect(model, SIGNAL(layoutAboutToBeChanged()),
                         this, SLOT(_q_sectionsAboutToBeChanged()));
        QObject::connect(model, SIGNAL(layoutChanged()),
                         this, SLOT(_q_sectionsChanged()));
    }

    d->state = QHeaderViewPrivate::NoClear;
    QAbstractItemView::setModel(model);
    d->state = QHeaderViewPrivate::NoState;

    // Users want to set sizes and modes before the widget is shown.
    // Thus, we have to initialize when the model is set,
    // and not lazily like we do in the other views.
    initializeSections();
}

/*!
    Returns the orientation of the header.

    \sa Qt::Orientation
*/

Qt::Orientation QHeaderView::orientation() const
{
    Q_D(const QHeaderView);
    return d->orientation;
}

/*!
    Returns the offset of the header: this is the header's left-most (or
    top-most for vertical headers) visible pixel.

    \sa setOffset()
*/

int QHeaderView::offset() const
{
    Q_D(const QHeaderView);
    return d->offset;
}

/*!
    \fn void QHeaderView::setOffset(int offset)

    Sets the header's offset to \a offset.

    \sa offset(), length()
*/

void QHeaderView::setOffset(int newOffset)
{
    Q_D(QHeaderView);
    if (d->offset == (int)newOffset)
        return;
    int ndelta = d->offset - newOffset;
    d->offset = newOffset;
    if (d->orientation == Qt::Horizontal)
        d->viewport->scroll(isRightToLeft() ? -ndelta : ndelta, 0);
    else
        d->viewport->scroll(0, ndelta);
    if (d->state == QHeaderViewPrivate::ResizeSection && !d->preventCursorChangeInSetOffset) {
        QPoint cursorPos = QCursor::pos();
        if (d->orientation == Qt::Horizontal)
            QCursor::setPos(cursorPos.x() + ndelta, cursorPos.y());
        else
            QCursor::setPos(cursorPos.x(), cursorPos.y() + ndelta);
        d->firstPos += ndelta;
        d->lastPos += ndelta;
    }
}

/*!
    \since 4.2
    Sets the offset to the start of the section at the given \a visualSectionNumber.
    \a visualSectionNumber is the actual visible section when hiddenSections are
    not considered. That is not always the same as visualIndex().

    \sa setOffset(), sectionPosition()
*/
void QHeaderView::setOffsetToSectionPosition(int visualSectionNumber)
{
    Q_D(QHeaderView);
    if (visualSectionNumber > -1 && visualSectionNumber < d->sectionCount()) {
        int position = d->headerSectionPosition(d->adjustedVisualIndex(visualSectionNumber));
        setOffset(position);
    }
}

/*!
    \since 4.2
    Sets the offset to make the last section visible.

    \sa setOffset(), sectionPosition(), setOffsetToSectionPosition()
*/
void QHeaderView::setOffsetToLastSection()
{
    Q_D(const QHeaderView);
    int size = (d->orientation == Qt::Horizontal ? viewport()->width() : viewport()->height());
    int position = length() - size;
    setOffset(position);
}

/*!
    Returns the length along the orientation of the header.

    \sa sizeHint(), setSectionResizeMode(), offset()
*/

int QHeaderView::length() const
{
    Q_D(const QHeaderView);
    d->executePostedLayout();
    d->executePostedResize();
    //Q_ASSERT(d->headerLength() == d->length);
    return d->length;
}

/*!
    Returns a suitable size hint for this header.

    \sa sectionSizeHint()
*/

QSize QHeaderView::sizeHint() const
{
    Q_D(const QHeaderView);
    if (d->cachedSizeHint.isValid())
        return d->cachedSizeHint;
    d->cachedSizeHint = QSize(0, 0); //reinitialize the cached size hint
    const int sectionCount = count();

    // get size hint for the first n sections
    int i = 0;
    for (int checked = 0; checked < 100 && i < sectionCount; ++i) {
        if (isSectionHidden(i))
            continue;
        checked++;
        QSize hint = sectionSizeFromContents(i);
        d->cachedSizeHint = d->cachedSizeHint.expandedTo(hint);
    }
    // get size hint for the last n sections
    i = qMax(i, sectionCount - 100 );
    for (int j = sectionCount - 1, checked = 0; j >= i && checked < 100; --j) {
        if (isSectionHidden(j))
            continue;
        checked++;
        QSize hint = sectionSizeFromContents(j);
        d->cachedSizeHint = d->cachedSizeHint.expandedTo(hint);
    }
    return d->cachedSizeHint;
}

/*!
    \reimp
*/

void QHeaderView::setVisible(bool v)
{
    bool actualChange = (v != isVisible());
    QAbstractItemView::setVisible(v);
    if (actualChange) {
        QAbstractScrollArea *parent = qobject_cast<QAbstractScrollArea*>(parentWidget());
        if (parent)
            parent->updateGeometry();
    }
}


/*!
    Returns a suitable size hint for the section specified by \a logicalIndex.

    \sa sizeHint(), defaultSectionSize(), minimumSectionSize(), maximumSectionSize()
    Qt::SizeHintRole
*/

int QHeaderView::sectionSizeHint(int logicalIndex) const
{
    Q_D(const QHeaderView);
    if (isSectionHidden(logicalIndex))
        return 0;
    if (logicalIndex < 0 || logicalIndex >= count())
        return -1;
    QSize size;
    QVariant value = d->model->headerData(logicalIndex, d->orientation, Qt::SizeHintRole);
    if (value.isValid())
        size = qvariant_cast<QSize>(value);
    else
        size = sectionSizeFromContents(logicalIndex);
    int hint = d->orientation == Qt::Horizontal ? size.width() : size.height();
    return qBound(minimumSectionSize(), hint, maximumSectionSize());
}

/*!
    Returns the visual index of the section that covers the given \a position
    in the viewport.

    \sa logicalIndexAt()
*/

int QHeaderView::visualIndexAt(int position) const
{
    Q_D(const QHeaderView);
    int vposition = position;
    d->executePostedLayout();
    d->executePostedResize();
    const int count = d->sectionCount();
    if (count < 1)
        return -1;

    if (d->reverse())
        vposition = d->viewport->width() - vposition;
    vposition += d->offset;

    if (vposition > d->length)
        return -1;
    int visual = d->headerVisualIndexAt(vposition);
    if (visual < 0)
        return -1;

    while (d->isVisualIndexHidden(visual)){
        ++visual;
        if (visual >= count)
            return -1;
    }
    return visual;
}

/*!
    Returns the section that covers the given \a position in the viewport.

    \sa visualIndexAt(), isSectionHidden()
*/

int QHeaderView::logicalIndexAt(int position) const
{
    const int visual = visualIndexAt(position);
    if (visual > -1)
        return logicalIndex(visual);
    return -1;
}

/*!
    Returns the width (or height for vertical headers) of the given
    \a logicalIndex.

    \sa length(), setSectionResizeMode(), defaultSectionSize()
*/

int QHeaderView::sectionSize(int logicalIndex) const
{
    Q_D(const QHeaderView);
    if (isSectionHidden(logicalIndex))
        return 0;
    if (logicalIndex < 0 || logicalIndex >= count())
        return 0;
    int visual = visualIndex(logicalIndex);
    if (visual == -1)
        return 0;
    d->executePostedResize();
    return d->headerSectionSize(visual);
}

/*!

    Returns the section position of the given \a logicalIndex, or -1
    if the section is hidden. The position is measured in pixels from
    the first visible item's top-left corner to the top-left corner of
    the item with \a logicalIndex. The measurement is along the x-axis
    for horizontal headers and along the y-axis for vertical headers.

    \sa sectionViewportPosition()
*/

int QHeaderView::sectionPosition(int logicalIndex) const
{
    Q_D(const QHeaderView);
    int visual = visualIndex(logicalIndex);
    // in some cases users may change the selections
    // before we have a chance to do the layout
    if (visual == -1)
        return -1;
    d->executePostedResize();
    return d->headerSectionPosition(visual);
}

/*!
    Returns the section viewport position of the given \a logicalIndex.

    If the section is hidden, the return value is undefined.

    \sa sectionPosition(), isSectionHidden()
*/

int QHeaderView::sectionViewportPosition(int logicalIndex) const
{
    Q_D(const QHeaderView);
    if (logicalIndex >= count())
        return -1;
    int position = sectionPosition(logicalIndex);
    if (position < 0)
        return position; // the section was hidden
    int offsetPosition = position - d->offset;
    if (d->reverse())
        return d->viewport->width() - (offsetPosition + sectionSize(logicalIndex));
    return offsetPosition;
}

/*!
    \fn int QHeaderView::logicalIndexAt(int x, int y) const

    Returns the logical index of the section at the given coordinate. If the
    header is horizontal \a x will be used, otherwise \a y will be used to
    find the logical index.
*/

/*!
    \fn int QHeaderView::logicalIndexAt(const QPoint &pos) const

    Returns the logical index of the section at the position given in \a pos.
    If the header is horizontal the x-coordinate will be used, otherwise the
    y-coordinate will be used to find the logical index.

    \sa sectionPosition()
*/

template<typename Container>
static void qMoveRange(Container& c,
               typename Container::size_type rangeStart,
               typename Container::size_type rangeEnd,
               typename Container::size_type targetPosition)
{
    Q_ASSERT(targetPosition <= c.size());
    Q_ASSERT(targetPosition < rangeStart || targetPosition >= rangeEnd);

    const bool forwardMove = targetPosition > rangeStart;
    typename Container::size_type first = std::min(rangeStart, targetPosition);
    typename Container::size_type mid = forwardMove ? rangeEnd : rangeStart;
    typename Container::size_type last = forwardMove ? targetPosition + 1 : rangeEnd;
    std::rotate(c.begin() + first, c.begin() + mid, c.begin() + last);
}

/*!
    Moves the section at visual index \a from to occupy visual index \a to.

    \sa sectionsMoved()
*/

void QHeaderView::moveSection(int from, int to)
{
    Q_D(QHeaderView);

    d->executePostedLayout();
    if (from < 0 || from >= d->sectionCount() || to < 0 || to >= d->sectionCount())
        return;

    if (from == to) {
        int logical = logicalIndex(from);
        Q_ASSERT(logical != -1);
        updateSection(logical);
        return;
    }

    d->initializeIndexMapping();

    int *visualIndices = d->visualIndices.data();
    int *logicalIndices = d->logicalIndices.data();
    int logical = logicalIndices[from];
    int visual = from;

    if (to > from) {
        while (visual < to) {
            visualIndices[logicalIndices[visual + 1]] = visual;
            logicalIndices[visual] = logicalIndices[visual + 1];
            ++visual;
        }
    } else {
        while (visual > to) {
            visualIndices[logicalIndices[visual - 1]] = visual;
            logicalIndices[visual] = logicalIndices[visual - 1];
            --visual;
        }
    }
    visualIndices[logical] = to;
    logicalIndices[to] = logical;

    qMoveRange(d->sectionItems, from, from + 1, to);

    d->sectionStartposRecalc = true;

    if (d->hasAutoResizeSections())
        d->doDelayedResizeSections();
    d->viewport->update();

    emit sectionMoved(logical, from, to);

    if (stretchLastSection()) {
        const int lastSectionVisualIdx = visualIndex(d->lastSectionLogicalIdx);
        if (from >= lastSectionVisualIdx || to >= lastSectionVisualIdx)
            d->maybeRestorePrevLastSectionAndStretchLast();
    }
}

/*!
    \since 4.2
    Swaps the section at visual index \a first with the section at visual
    index \a second.

    \sa moveSection()
*/
void QHeaderView::swapSections(int first, int second)
{
    Q_D(QHeaderView);

    if (first == second)
        return;
    d->executePostedLayout();
    if (first < 0 || first >= d->sectionCount() || second < 0 || second >= d->sectionCount())
        return;

    int firstSize = d->headerSectionSize(first);
    ResizeMode firstMode = d->headerSectionResizeMode(first);
    int firstLogical = d->logicalIndex(first);

    int secondSize = d->headerSectionSize(second);
    ResizeMode secondMode = d->headerSectionResizeMode(second);
    int secondLogical = d->logicalIndex(second);

    if (d->state == QHeaderViewPrivate::ResizeSection)
        d->preventCursorChangeInSetOffset = true;

    d->createSectionItems(second, second, firstSize, firstMode);
    d->createSectionItems(first, first, secondSize, secondMode);

    d->initializeIndexMapping();

    d->visualIndices[firstLogical] = second;
    d->logicalIndices[second] = firstLogical;

    d->visualIndices[secondLogical] = first;
    d->logicalIndices[first] = secondLogical;

    if (!d->hiddenSectionSize.isEmpty()) {
        bool firstHidden = d->isVisualIndexHidden(first);
        bool secondHidden = d->isVisualIndexHidden(second);
        d->setVisualIndexHidden(first, secondHidden);
        d->setVisualIndexHidden(second, firstHidden);
    }

    d->viewport->update();
    emit sectionMoved(firstLogical, first, second);
    emit sectionMoved(secondLogical, second, first);

    if (stretchLastSection()) {
        const int lastSectionVisualIdx = visualIndex(d->lastSectionLogicalIdx);
        if (first >= lastSectionVisualIdx || second >= lastSectionVisualIdx)
            d->maybeRestorePrevLastSectionAndStretchLast();
    }
}

/*!
    \fn void QHeaderView::resizeSection(int logicalIndex, int size)

    Resizes the section specified by \a logicalIndex to \a size measured in
    pixels. The size parameter must be a value larger or equal to zero. A
    size equal to zero is however not recommended. In that situation hideSection
    should be used instead.

    \sa sectionResized(), resizeMode(), sectionSize(), hideSection()
*/

void QHeaderView::resizeSection(int logical, int size)
{
    Q_D(QHeaderView);
    if (logical < 0 || logical >= count() || size < 0 || size > maxSizeSection)
        return;

    if (isSectionHidden(logical)) {
        d->hiddenSectionSize.insert(logical, size);
        return;
    }

    int visual = visualIndex(logical);
    if (visual == -1)
        return;

    if (d->state == QHeaderViewPrivate::ResizeSection && !d->cascadingResizing && logical != d->section)
        d->preventCursorChangeInSetOffset = true;

    int oldSize = d->headerSectionSize(visual);
    if (oldSize == size)
        return;

    d->executePostedLayout();
    d->invalidateCachedSizeHint();

    if (stretchLastSection() && logical == d->lastSectionLogicalIdx)
        d->lastSectionSize = size;

    d->createSectionItems(visual, visual, size, d->headerSectionResizeMode(visual));

    if (!updatesEnabled()) {
        if (d->hasAutoResizeSections())
            d->doDelayedResizeSections();
        emit sectionResized(logical, oldSize, size);
        return;
    }

    int w = d->viewport->width();
    int h = d->viewport->height();
    int pos = sectionViewportPosition(logical);
    QRect r;
    if (d->orientation == Qt::Horizontal)
        if (isRightToLeft())
            r.setRect(0, 0, pos + size, h);
        else
            r.setRect(pos, 0, w - pos, h);
    else
        r.setRect(0, pos, w, h - pos);

    if (d->hasAutoResizeSections()) {
        d->doDelayedResizeSections();
        r = d->viewport->rect();
    }

    // If the parent is a QAbstractScrollArea with QAbstractScrollArea::AdjustToContents
    // then we want to change the geometry on that widget. Not doing it at once can/will
    // cause scrollbars flicker as they would be shown at first but then removed.
    // In the same situation it will also allow shrinking the whole view when stretchLastSection is set
    // (It is default on QTreeViews - and it wouldn't shrink since the last stretch was made before the
    // viewport was resized)

    QAbstractScrollArea *parent = qobject_cast<QAbstractScrollArea *>(parentWidget());
    if (parent && parent->sizeAdjustPolicy() == QAbstractScrollArea::AdjustToContents)
        parent->updateGeometry();

    d->viewport->update(r.normalized());
    emit sectionResized(logical, oldSize, size);
}

/*!
    Resizes the sections according to the given \a mode, ignoring the current
    resize mode.

    \sa resizeMode(), sectionResized()
*/

void QHeaderView::resizeSections(QHeaderView::ResizeMode mode)
{
    Q_D(QHeaderView);
    d->resizeSections(mode, true);
}

/*!
    \fn void QHeaderView::hideSection(int logicalIndex)
    Hides the section specified by \a logicalIndex.

    \sa showSection(), isSectionHidden(), hiddenSectionCount(),
    setSectionHidden()
*/

/*!
    \fn void QHeaderView::showSection(int logicalIndex)
    Shows the section specified by \a logicalIndex.

    \sa hideSection(), isSectionHidden(), hiddenSectionCount(),
    setSectionHidden()
*/

/*!
    Returns \c true if the section specified by \a logicalIndex is explicitly
    hidden from the user; otherwise returns \c false.

    \sa hideSection(), showSection(), setSectionHidden(), hiddenSectionCount()
*/

bool QHeaderView::isSectionHidden(int logicalIndex) const
{
    Q_D(const QHeaderView);
    d->executePostedLayout();
    if (d->hiddenSectionSize.isEmpty() || logicalIndex < 0 || logicalIndex >= d->sectionCount())
        return false;
    int visual = visualIndex(logicalIndex);
    Q_ASSERT(visual != -1);
    return d->isVisualIndexHidden(visual);
}

/*!
    \since 4.1

    Returns the number of sections in the header that has been hidden.

    \sa setSectionHidden(), isSectionHidden()
*/
int QHeaderView::hiddenSectionCount() const
{
    Q_D(const QHeaderView);
    return d->hiddenSectionSize.count();
}

/*!
  If \a hide is true the section specified by \a logicalIndex is hidden;
  otherwise the section is shown.

  \sa isSectionHidden(), hiddenSectionCount()
*/

void QHeaderView::setSectionHidden(int logicalIndex, bool hide)
{
    Q_D(QHeaderView);
    if (logicalIndex < 0 || logicalIndex >= count())
        return;

    d->executePostedLayout();
    int visual = visualIndex(logicalIndex);
    Q_ASSERT(visual != -1);
    if (hide == d->isVisualIndexHidden(visual))
        return;
    if (hide) {
        const bool isHidingLastSection = (stretchLastSection() && logicalIndex == d->lastSectionLogicalIdx);
        if (isHidingLastSection)
            d->restoreSizeOnPrevLastSection(); // Restore here/now to get the right restore size.
        int size = d->headerSectionSize(visual);
        if (!d->hasAutoResizeSections())
            resizeSection(logicalIndex, 0);
        d->hiddenSectionSize.insert(logicalIndex, size);
        d->setVisualIndexHidden(visual, true);
        if (isHidingLastSection)
            d->setNewLastSection(d->lastVisibleVisualIndex());
        if (d->hasAutoResizeSections())
            d->doDelayedResizeSections();
    } else {
        int size = d->hiddenSectionSize.value(logicalIndex, d->defaultSectionSize);
        d->hiddenSectionSize.remove(logicalIndex);
        d->setVisualIndexHidden(visual, false);
        resizeSection(logicalIndex, size);

        const bool newLastSection = (stretchLastSection() && visual > visualIndex(d->lastSectionLogicalIdx));
        if (newLastSection) {
            d->restoreSizeOnPrevLastSection();
            d->setNewLastSection(visual);
        }
    }
}

/*!
    Returns the number of sections in the header.

    \sa sectionCountChanged(), length()
*/

int QHeaderView::count() const
{
    Q_D(const QHeaderView);
    //Q_ASSERT(d->sectionCount == d->headerSectionCount());
    // ### this may affect the lazy layout
    d->executePostedLayout();
    return d->sectionCount();
}

/*!
    Returns the visual index position of the section specified by the given
    \a logicalIndex, or -1 otherwise.

    Hidden sections still have valid visual indexes.

    \sa logicalIndex()
*/

int QHeaderView::visualIndex(int logicalIndex) const
{
    Q_D(const QHeaderView);
    if (logicalIndex < 0)
        return -1;
    d->executePostedLayout();
    if (d->visualIndices.isEmpty()) { // nothing has been moved, so we have no mapping
        if (logicalIndex < d->sectionCount())
            return logicalIndex;
    } else if (logicalIndex < d->visualIndices.count()) {
        int visual = d->visualIndices.at(logicalIndex);
        Q_ASSERT(visual < d->sectionCount());
        return visual;
    }
    return -1;
}

/*!
    Returns the logicalIndex for the section at the given \a visualIndex
    position, or -1 if visualIndex < 0 or visualIndex >= QHeaderView::count().

    Note that the visualIndex is not affected by hidden sections.

    \sa visualIndex(), sectionPosition()
*/

int QHeaderView::logicalIndex(int visualIndex) const
{
    Q_D(const QHeaderView);
    if (visualIndex < 0 || visualIndex >= d->sectionCount())
        return -1;
    return d->logicalIndex(visualIndex);
}

/*!
    \since 5.0

    If \a movable is true, the header sections may be moved by the user;
    otherwise they are fixed in place.

    When used in combination with QTreeView, the first column is not
    movable (since it contains the tree structure), by default.
    You can make it movable with setFirstSectionMovable(true).

    \sa sectionsMovable(), sectionMoved()
    \sa setFirstSectionMovable()
*/

void QHeaderView::setSectionsMovable(bool movable)
{
    Q_D(QHeaderView);
    d->movableSections = movable;
}

// ### Qt 6 - remove this obsolete function
/*!
    \obsolete
    \fn void QHeaderView::setMovable(bool movable)

    Use setSectionsMovable instead.

    \sa setSectionsMovable()
*/

/*!
    \since 5.0

    Returns \c true if the header can be moved by the user; otherwise returns
    false.

    By default, sections are movable in QTreeView (except for the first one),
    and not movable in QTableView.

    \sa setSectionsMovable()
*/

bool QHeaderView::sectionsMovable() const
{
    Q_D(const QHeaderView);
    return d->movableSections;
}

// ### Qt 6 - remove this obsolete function
/*!
    \obsolete
    \fn bool QHeaderView::isMovable() const

    Use sectionsMovable instead.

    \sa sectionsMovable()
*/

/*!
    \since 5.10

    If \a movable is true, the first column can be moved by the user.
    In a QTreeView, the first column holds the tree structure and is
    therefore non-movable by default, even after setSectionsMovable(true).

    It can be made movable again, for instance in the case of flat lists
    without a tree structure, by calling this method.
    In such a scenario, it is recommended to call QTreeView::setRootIsDecorated(false)
    as well.

    This method has no effect unless setSectionsMovable(true) is called as well.
    \sa setSectionsMovable()
*/
void QHeaderView::setFirstSectionMovable(bool movable)
{
    Q_D(QHeaderView);
    d->allowUserMoveOfSection0 = movable;
}

/*!
    \since 5.10

    Returns \c true if the first column can be moved by the user,
    when this header is used in a QTreeView.
*/
bool QHeaderView::firstSectionMovable() const
{
    Q_D(const QHeaderView);
    return d->allowUserMoveOfSection0;
}

/*!
    \since 5.0

    If \a clickable is true, the header will respond to single clicks.

    \sa sectionsClickable(), sectionClicked(), sectionPressed(),
    setSortIndicatorShown()
*/

void QHeaderView::setSectionsClickable(bool clickable)
{
    Q_D(QHeaderView);
    d->clickableSections = clickable;
}

// ### Qt 6 - remove this obsolete function
/*!
    \obsolete
    \fn void QHeaderView::setClickable(bool clickable)

    Use setSectionsClickable instead.

    \sa setSectionsClickable()
*/

/*!
    \since 5.0

    Returns \c true if the header is clickable; otherwise returns \c false. A
    clickable header could be set up to allow the user to change the
    representation of the data in the view related to the header.

    \sa setSectionsClickable()
*/

bool QHeaderView::sectionsClickable() const
{
    Q_D(const QHeaderView);
    return d->clickableSections;
}

// ### Qt 6 - remove this obsolete function
/*!
    \obsolete
    \fn bool QHeaderView::isClickable() const

    Use sectionsClickable instead.

    \sa sectionsClickable()
*/

void QHeaderView::setHighlightSections(bool highlight)
{
    Q_D(QHeaderView);
    d->highlightSelected = highlight;
}

bool QHeaderView::highlightSections() const
{
    Q_D(const QHeaderView);
    return d->highlightSelected;
}

/*!
    \since 5.0

    Sets the constraints on how the header can be resized to those described
    by the given \a mode.

    \sa resizeMode(), length(), sectionResized()
*/

void QHeaderView::setSectionResizeMode(ResizeMode mode)
{
    Q_D(QHeaderView);
    initializeSections();
    d->stretchSections = (mode == Stretch ? count() : 0);
    d->contentsSections =  (mode == ResizeToContents ? count() : 0);
    d->setGlobalHeaderResizeMode(mode);
    if (d->hasAutoResizeSections())
        d->doDelayedResizeSections(); // section sizes may change as a result of the new mode
}

/*!
    \since 5.0

    Sets the constraints on how the section specified by \a logicalIndex in
    the header can be resized to those described by the given \a mode. The logical
    index should exist at the time this function is called.

    \note This setting will be ignored for the last section if the stretchLastSection
    property is set to true. This is the default for the horizontal headers provided
    by QTreeView.

    \sa setStretchLastSection(), resizeContentsPrecision()
*/

void QHeaderView::setSectionResizeMode(int logicalIndex, ResizeMode mode)
{
    Q_D(QHeaderView);
    int visual = visualIndex(logicalIndex);
    Q_ASSERT(visual != -1);

    ResizeMode old = d->headerSectionResizeMode(visual);
    d->setHeaderSectionResizeMode(visual, mode);

    if (mode == Stretch && old != Stretch)
        ++d->stretchSections;
    else if (mode == ResizeToContents && old != ResizeToContents)
        ++d->contentsSections;
    else if (mode != Stretch && old == Stretch)
        --d->stretchSections;
    else if (mode != ResizeToContents && old == ResizeToContents)
        --d->contentsSections;

    if (d->hasAutoResizeSections() && d->state == QHeaderViewPrivate::NoState)
        d->doDelayedResizeSections(); // section sizes may change as a result of the new mode
}

// ### Qt 6 - remove this obsolete function
/*!
    \overload
    \obsolete
    \fn void QHeaderView::setResizeMode(int logicalIndex, ResizeMode mode)

    Use setSectionResizeMode instead.

    \sa setSectionResizeMode()
*/

/*!
    \obsolete
    \fn void QHeaderView::setResizeMode(ResizeMode mode)

    Use setSectionResizeMode instead.

    \sa setSectionResizeMode()
*/

/*!
    \since 5.0

    Returns the resize mode that applies to the section specified by the given
    \a logicalIndex.

    \sa setSectionResizeMode()
*/

QHeaderView::ResizeMode QHeaderView::sectionResizeMode(int logicalIndex) const
{
    Q_D(const QHeaderView);
    int visual = visualIndex(logicalIndex);
    if (visual == -1)
        return Fixed; //the default value
    return d->headerSectionResizeMode(visual);
}

/*!
   \since 5.2
   Sets how precise QHeaderView should calculate the size when ResizeToContents is used.
   A low value will provide a less accurate but fast auto resize while a higher
   value will provide a more accurate resize that however can be slow.

   The number \a precision specifies how many sections that should be consider
   when calculating the preferred size.

   The default value is 1000 meaning that a horizontal column with auto-resize will look
   at maximum 1000 rows on calculating when doing an auto resize.

   Special value 0 means that it will look at only the visible area.
   Special value -1 will imply looking at all elements.

   This value is used in QTableView::sizeHintForColumn(), QTableView::sizeHintForRow()
   and QTreeView::sizeHintForColumn(). Reimplementing these functions can make this
   function not having an effect.

    \sa resizeContentsPrecision(), setSectionResizeMode(), resizeSections(), QTableView::sizeHintForColumn(), QTableView::sizeHintForRow(), QTreeView::sizeHintForColumn()
*/

void QHeaderView::setResizeContentsPrecision(int precision)
{
    Q_D(QHeaderView);
    d->resizeContentsPrecision = precision;
}

/*!
  \since 5.2
  Returns how precise QHeaderView will calculate on ResizeToContents.

  \sa setResizeContentsPrecision(), setSectionResizeMode()

*/

int QHeaderView::resizeContentsPrecision() const
{
    Q_D(const QHeaderView);
    return d->resizeContentsPrecision;
}

// ### Qt 6 - remove this obsolete function
/*!
    \obsolete
    \fn QHeaderView::ResizeMode QHeaderView::resizeMode(int logicalIndex) const

    Use sectionResizeMode instead.

    \sa sectionResizeMode()
*/

/*!
    \since 4.1

    Returns the number of sections that are set to resize mode stretch. In
    views, this can be used to see if the headerview needs to resize the
    sections when the view's geometry changes.

    \sa stretchLastSection, resizeMode()
*/

int QHeaderView::stretchSectionCount() const
{
    Q_D(const QHeaderView);
    return d->stretchSections;
}

/*!
  \property QHeaderView::showSortIndicator
  \brief whether the sort indicator is shown

  By default, this property is \c false.

  \sa setSectionsClickable()
*/

void QHeaderView::setSortIndicatorShown(bool show)
{
    Q_D(QHeaderView);
    if (d->sortIndicatorShown == show)
        return;

    d->sortIndicatorShown = show;

    if (sortIndicatorSection() < 0 || sortIndicatorSection() > count())
        return;

    if (d->headerSectionResizeMode(sortIndicatorSection()) == ResizeToContents)
        resizeSections();

    d->viewport->update();
}

bool QHeaderView::isSortIndicatorShown() const
{
    Q_D(const QHeaderView);
    return d->sortIndicatorShown;
}

/*!
    Sets the sort indicator for the section specified by the given
    \a logicalIndex in the direction specified by \a order, and removes the
    sort indicator from any other section that was showing it.

    \a logicalIndex may be -1, in which case no sort indicator will be shown
    and the model will return to its natural, unsorted order. Note that not
    all models support this and may even crash in this case.

    \sa sortIndicatorSection(), sortIndicatorOrder()
*/

void QHeaderView::setSortIndicator(int logicalIndex, Qt::SortOrder order)
{
    Q_D(QHeaderView);

    // This is so that people can set the position of the sort indicator before the fill the model
    int old = d->sortIndicatorSection;
    if (old == logicalIndex && order == d->sortIndicatorOrder)
        return;
    d->sortIndicatorSection = logicalIndex;
    d->sortIndicatorOrder = order;

    if (logicalIndex >= d->sectionCount()) {
        emit sortIndicatorChanged(logicalIndex, order);
        return; // nothing to do
    }

    if (old != logicalIndex
        && ((logicalIndex >= 0 && sectionResizeMode(logicalIndex) == ResizeToContents)
            || old >= d->sectionCount() || (old >= 0 && sectionResizeMode(old) == ResizeToContents))) {
        resizeSections();
        d->viewport->update();
    } else {
        if (old >= 0 && old != logicalIndex)
            updateSection(old);
        if (logicalIndex >= 0)
            updateSection(logicalIndex);
    }

    emit sortIndicatorChanged(logicalIndex, order);
}

/*!
    Returns the logical index of the section that has a sort indicator.
    By default this is section 0.

    \sa setSortIndicator(), sortIndicatorOrder(), setSortIndicatorShown()
*/

int QHeaderView::sortIndicatorSection() const
{
    Q_D(const QHeaderView);
    return d->sortIndicatorSection;
}

/*!
    Returns the order for the sort indicator. If no section has a sort
    indicator the return value of this function is undefined.

    \sa setSortIndicator(), sortIndicatorSection()
*/

Qt::SortOrder QHeaderView::sortIndicatorOrder() const
{
    Q_D(const QHeaderView);
    return d->sortIndicatorOrder;
}

/*!
    \property QHeaderView::stretchLastSection
    \brief whether the last visible section in the header takes up all the
    available space

    The default value is false.

    \note The horizontal headers provided by QTreeView are configured with this
    property set to true, ensuring that the view does not waste any of the
    space assigned to it for its header. If this value is set to true, this
    property will override the resize mode set on the last section in the
    header.

    \sa setSectionResizeMode()
*/
bool QHeaderView::stretchLastSection() const
{
    Q_D(const QHeaderView);
    return d->stretchLastSection;
}

void QHeaderView::setStretchLastSection(bool stretch)
{
    Q_D(QHeaderView);
    if (d->stretchLastSection == stretch)
        return;
    d->stretchLastSection = stretch;
    if (d->state != QHeaderViewPrivate::NoState)
        return;
    if (stretch) {
        d->setNewLastSection(d->lastVisibleVisualIndex());
        resizeSections();
    } else {
        d->restoreSizeOnPrevLastSection();
    }
}

/*!
    \since 4.2
    \property QHeaderView::cascadingSectionResizes
    \brief whether interactive resizing will be cascaded to the following
    sections once the section being resized by the user has reached its
    minimum size

    This property only affects sections that have \l Interactive as their
    resize mode.

    The default value is false.

    \sa setSectionResizeMode()
*/
bool QHeaderView::cascadingSectionResizes() const
{
    Q_D(const QHeaderView);
    return d->cascadingResizing;
}

void QHeaderView::setCascadingSectionResizes(bool enable)
{
    Q_D(QHeaderView);
    d->cascadingResizing = enable;
}

/*!
    \property QHeaderView::defaultSectionSize
    \brief the default size of the header sections before resizing.

    This property only affects sections that have \l Interactive or \l Fixed
    as their resize mode.

    By default, the value of this property is style dependent.
    Thus, when the style changes, this property updates from it.
    Calling setDefaultSectionSize() stops the updates, calling
    resetDefaultSectionSize() will restore default behavior.

    \sa setSectionResizeMode(), minimumSectionSize
*/
int QHeaderView::defaultSectionSize() const
{
    Q_D(const QHeaderView);
    return d->defaultSectionSize;
}

void QHeaderView::setDefaultSectionSize(int size)
{
    Q_D(QHeaderView);
    if (size < 0 || size > maxSizeSection)
        return;
    d->setDefaultSectionSize(size);
}

void QHeaderView::resetDefaultSectionSize()
{
    Q_D(QHeaderView);
    if (d->customDefaultSectionSize) {
        d->updateDefaultSectionSizeFromStyle();
        d->customDefaultSectionSize = false;
    }
}

/*!
    \since 4.2
    \property QHeaderView::minimumSectionSize
    \brief the minimum size of the header sections.

    The minimum section size is the smallest section size allowed. If the
    minimum section size is set to -1, QHeaderView will use the maximum of
    the \l{QApplication::globalStrut()}{global strut} or the
    \l{fontMetrics()}{font metrics} size.

    This property is honored by all \l{ResizeMode}{resize modes}.

    \sa setSectionResizeMode(), defaultSectionSize
*/
int QHeaderView::minimumSectionSize() const
{
    Q_D(const QHeaderView);
    if (d->minimumSectionSize == -1) {
        QSize strut = QApplication::globalStrut();
        int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, 0, this);
        if (d->orientation == Qt::Horizontal)
            return qMax(strut.width(), (fontMetrics().maxWidth() + margin));
        return qMax(strut.height(), (fontMetrics().height() + margin));
    }
    return d->minimumSectionSize;
}

void QHeaderView::setMinimumSectionSize(int size)
{
    Q_D(QHeaderView);
    if (size < -1 || size > maxSizeSection)
        return;
    d->minimumSectionSize = size;
    if (d->minimumSectionSize > maximumSectionSize())
        d->maximumSectionSize = size;
}

/*!
    \since 5.2
    \property QHeaderView::maximumSectionSize
    \brief the maximum size of the header sections.

    The maximum section size is the largest section size allowed.
    The default value for this property is 1048575, which is also the largest
    possible size for a section. Setting maximum to -1 will reset the value to
    the largest section size.

    With exception of stretch this property is honored by all \l{ResizeMode}{resize modes}

    \sa setSectionResizeMode(), defaultSectionSize
*/
int QHeaderView::maximumSectionSize() const
{
    Q_D(const QHeaderView);
    if (d->maximumSectionSize == -1)
        return maxSizeSection;
    return d->maximumSectionSize;
}

void QHeaderView::setMaximumSectionSize(int size)
{
    Q_D(QHeaderView);
    if (size == -1) {
        d->maximumSectionSize = maxSizeSection;
        return;
    }
    if (size < 0 || size > maxSizeSection)
        return;
    if (minimumSectionSize() > size)
        d->minimumSectionSize = size;

    d->maximumSectionSize = size;
}


/*!
    \since 4.1
    \property QHeaderView::defaultAlignment
    \brief the default alignment of the text in each header section
*/

Qt::Alignment QHeaderView::defaultAlignment() const
{
    Q_D(const QHeaderView);
    return d->defaultAlignment;
}

void QHeaderView::setDefaultAlignment(Qt::Alignment alignment)
{
    Q_D(QHeaderView);
    if (d->defaultAlignment == alignment)
        return;

    d->defaultAlignment = alignment;
    d->viewport->update();
}

/*!
    \internal
*/
void QHeaderView::doItemsLayout()
{
    initializeSections();
    QAbstractItemView::doItemsLayout();
}

/*!
    Returns \c true if sections in the header has been moved; otherwise returns
    false;

    \sa moveSection()
*/
bool QHeaderView::sectionsMoved() const
{
    Q_D(const QHeaderView);
    return !d->visualIndices.isEmpty();
}

/*!
    \since 4.1

    Returns \c true if sections in the header has been hidden; otherwise returns
    false;

    \sa setSectionHidden()
*/
bool QHeaderView::sectionsHidden() const
{
    Q_D(const QHeaderView);
    return !d->hiddenSectionSize.isEmpty();
}

#ifndef QT_NO_DATASTREAM
/*!
    \since 4.3

    Saves the current state of this header view.

    To restore the saved state, pass the return value to restoreState().

    \sa restoreState()
*/
QByteArray QHeaderView::saveState() const
{
    Q_D(const QHeaderView);
    QByteArray data;
    QDataStream stream(&data, QIODevice::WriteOnly);
    stream << QHeaderViewPrivate::VersionMarker;
    stream << 0; // current version is 0
    d->write(stream);
    return data;
}

/*!
    \since 4.3
    Restores the \a state of this header view.
    This function returns \c true if the state was restored; otherwise returns
    false.

    \sa saveState()
*/
bool QHeaderView::restoreState(const QByteArray &state)
{
    Q_D(QHeaderView);
    if (state.isEmpty())
        return false;
    QByteArray data = state;
    QDataStream stream(&data, QIODevice::ReadOnly);
    int marker;
    int ver;
    stream >> marker;
    stream >> ver;
    if (stream.status() != QDataStream::Ok
        || marker != QHeaderViewPrivate::VersionMarker
        || ver != 0) // current version is 0
        return false;

    if (d->read(stream)) {
        emit sortIndicatorChanged(d->sortIndicatorSection, d->sortIndicatorOrder );
        d->viewport->update();
        return true;
    }
    return false;
}
#endif // QT_NO_DATASTREAM

/*!
  \reimp
*/
void QHeaderView::reset()
{
    QAbstractItemView::reset();
    // it would be correct to call clear, but some apps rely
    // on the header keeping the sections, even after calling reset
    //d->clear();
    initializeSections();
}

/*!
    Updates the changed header sections with the given \a orientation, from
    \a logicalFirst to \a logicalLast inclusive.
*/
void QHeaderView::headerDataChanged(Qt::Orientation orientation, int logicalFirst, int logicalLast)
{
    Q_D(QHeaderView);
    if (d->orientation != orientation)
        return;

    if (logicalFirst < 0 || logicalLast < 0 || logicalFirst >= count() || logicalLast >= count())
        return;

    d->invalidateCachedSizeHint();

    int firstVisualIndex = INT_MAX, lastVisualIndex = -1;

    for (int section = logicalFirst; section <= logicalLast; ++section) {
        const int visual = visualIndex(section);
        firstVisualIndex = qMin(firstVisualIndex, visual);
        lastVisualIndex =  qMax(lastVisualIndex,  visual);
    }

    d->executePostedResize();
    const int first = d->headerSectionPosition(firstVisualIndex),
              last = d->headerSectionPosition(lastVisualIndex)
                        + d->headerSectionSize(lastVisualIndex);

    if (orientation == Qt::Horizontal) {
        d->viewport->update(first, 0, last - first, d->viewport->height());
    } else {
        d->viewport->update(0, first, d->viewport->width(), last - first);
    }
}

/*!
    \internal
    \since 4.2

    Updates the section specified by the given \a logicalIndex.
*/

void QHeaderView::updateSection(int logicalIndex)
{
    Q_D(QHeaderView);
    if (d->orientation == Qt::Horizontal)
        d->viewport->update(QRect(sectionViewportPosition(logicalIndex),
                                  0, sectionSize(logicalIndex), d->viewport->height()));
    else
        d->viewport->update(QRect(0, sectionViewportPosition(logicalIndex),
                                  d->viewport->width(), sectionSize(logicalIndex)));
}

/*!
    Resizes the sections according to their size hints. Normally, you do not
    have to call this function.
*/

void QHeaderView::resizeSections()
{
    Q_D(QHeaderView);
    if (d->hasAutoResizeSections())
        d->resizeSections(Interactive, false); // no global resize mode
}

/*!
    This slot is called when sections are inserted into the \a parent.
    \a logicalFirst and \a logicalLast indices signify where the new sections
    were inserted.

    If only one section is inserted, \a logicalFirst and \a logicalLast will
    be the same.
*/

void QHeaderView::sectionsInserted(const QModelIndex &parent,
                                   int logicalFirst, int logicalLast)
{
    Q_D(QHeaderView);
    if (parent != d->root)
        return; // we only handle changes in the root level
    int oldCount = d->sectionCount();

    d->invalidateCachedSizeHint();

    if (d->state == QHeaderViewPrivate::ResizeSection)
        d->preventCursorChangeInSetOffset = true;

    // add the new sections
    int insertAt = logicalFirst;
    int insertCount = logicalLast - logicalFirst + 1;

    bool lastSectionActualChange = false;
    if (stretchLastSection()) {

        int visualIndexForStretch = d->lastSectionLogicalIdx;
        if (d->lastSectionLogicalIdx >= 0 && d->lastSectionLogicalIdx < d->visualIndices.size())
            visualIndexForStretch = d->visualIndices[d->lastSectionLogicalIdx]; // We cannot call visualIndex since it executes executePostedLayout()
                                                                                // and it is likely to bypass initializeSections() and we may end up here again. Doing the insert twice.

        if (d->lastSectionLogicalIdx < 0 || insertAt >= visualIndexForStretch)
            lastSectionActualChange = true;

        if (d->lastSectionLogicalIdx >= logicalFirst)
            d->lastSectionLogicalIdx += insertCount; // We do not want to emit resize before we have fixed the count
    }

    QHeaderViewPrivate::SectionItem section(d->defaultSectionSize, d->globalResizeMode);
    d->sectionStartposRecalc = true;

    if (d->sectionItems.isEmpty() || insertAt >= d->sectionItems.count()) {
        int insertLength = d->defaultSectionSize * insertCount;
        d->length += insertLength;
        d->sectionItems.insert(d->sectionItems.count(), insertCount, section); // append
    } else {
        // separate them out into their own sections
        int insertLength = d->defaultSectionSize * insertCount;
        d->length += insertLength;
        d->sectionItems.insert(insertAt, insertCount, section);
    }

    // update sorting column
    if (d->sortIndicatorSection >= logicalFirst)
        d->sortIndicatorSection += insertCount;

    // update resize mode section counts
    if (d->globalResizeMode == Stretch)
        d->stretchSections = d->sectionCount();
    else if (d->globalResizeMode == ResizeToContents)
        d->contentsSections = d->sectionCount();

    // clear selection cache
    d->sectionSelected.clear();

    // update mapping
    if (!d->visualIndices.isEmpty() && !d->logicalIndices.isEmpty()) {
        Q_ASSERT(d->visualIndices.count() == d->logicalIndices.count());
        int mappingCount = d->visualIndices.count();
        for (int i = 0; i < mappingCount; ++i) {
            if (d->visualIndices.at(i) >= logicalFirst)
               d->visualIndices[i] += insertCount;
            if (d->logicalIndices.at(i) >= logicalFirst)
                d->logicalIndices[i] += insertCount;
        }
        for (int j = logicalFirst; j <= logicalLast; ++j) {
            d->visualIndices.insert(j, j);
            d->logicalIndices.insert(j, j);
        }
    }

    // insert sections into hiddenSectionSize
    QHash<int, int> newHiddenSectionSize; // from logical index to section size
    for (QHash<int, int>::const_iterator it = d->hiddenSectionSize.cbegin(),
         end = d->hiddenSectionSize.cend(); it != end; ++it) {
        const int oldIndex = it.key();
        const int newIndex = (oldIndex < logicalFirst) ? oldIndex : oldIndex + insertCount;
        newHiddenSectionSize[newIndex] = it.value();
    }
    d->hiddenSectionSize.swap(newHiddenSectionSize);

    d->doDelayedResizeSections();
    emit sectionCountChanged(oldCount, count());

    if (lastSectionActualChange)
        d->maybeRestorePrevLastSectionAndStretchLast();

    // if the new sections were not updated by resizing, we need to update now
    if (!d->hasAutoResizeSections())
        d->viewport->update();
}

/*!
    This slot is called when sections are removed from the \a parent.
    \a logicalFirst and \a logicalLast signify where the sections were removed.

    If only one section is removed, \a logicalFirst and \a logicalLast will
    be the same.
*/

void QHeaderView::sectionsAboutToBeRemoved(const QModelIndex &parent,
                                           int logicalFirst, int logicalLast)
{
    Q_UNUSED(parent);
    Q_UNUSED(logicalFirst);
    Q_UNUSED(logicalLast);
}

void QHeaderViewPrivate::updateHiddenSections(int logicalFirst, int logicalLast)
{
    Q_Q(QHeaderView);
    const int changeCount = logicalLast - logicalFirst + 1;

    // remove sections from hiddenSectionSize
    QHash<int, int> newHiddenSectionSize; // from logical index to section size
    for (int i = 0; i < logicalFirst; ++i)
        if (q->isSectionHidden(i))
            newHiddenSectionSize[i] = hiddenSectionSize[i];
    for (int j = logicalLast + 1; j < sectionCount(); ++j)
        if (q->isSectionHidden(j))
            newHiddenSectionSize[j - changeCount] = hiddenSectionSize[j];
    hiddenSectionSize = newHiddenSectionSize;
}

void QHeaderViewPrivate::_q_sectionsRemoved(const QModelIndex &parent,
                                            int logicalFirst, int logicalLast)
{
    Q_Q(QHeaderView);
    if (parent != root)
        return; // we only handle changes in the root level
    if (qMin(logicalFirst, logicalLast) < 0
        || qMax(logicalLast, logicalFirst) >= sectionCount())
        return;
    int oldCount = q->count();
    int changeCount = logicalLast - logicalFirst + 1;

    if (state == QHeaderViewPrivate::ResizeSection)
        preventCursorChangeInSetOffset = true;

    updateHiddenSections(logicalFirst, logicalLast);

    if (visualIndices.isEmpty() && logicalIndices.isEmpty()) {
        //Q_ASSERT(headerSectionCount() == sectionCount);
        removeSectionsFromSectionItems(logicalFirst, logicalLast);
    } else {
        if (logicalFirst == logicalLast) { // Remove just one index.
            int l = logicalFirst;
            int visual = visualIndices.at(l);
            Q_ASSERT(sectionCount() == logicalIndices.count());
            for (int v = 0; v < sectionCount(); ++v) {
                if (v > visual) {
                    int logical = logicalIndices.at(v);
                    --(visualIndices[logical]);
                }
                if (logicalIndex(v) > l) // no need to move the positions before l
                    --(logicalIndices[v]);
            }
            logicalIndices.remove(visual);
            visualIndices.remove(l);
            //Q_ASSERT(headerSectionCount() == sectionCount);
            removeSectionsFromSectionItems(visual, visual);
        } else {
            sectionStartposRecalc = true; // We will need to recalc positions after removing items
            for (int u = 0; u < sectionItems.count(); ++u)  // Store section info
                sectionItems.at(u).tmpLogIdx = logicalIndices.at(u);
            for (int v = sectionItems.count() - 1; v >= 0; --v) {  // Remove the sections
                if (logicalFirst <= sectionItems.at(v).tmpLogIdx && sectionItems.at(v).tmpLogIdx <= logicalLast)
                    removeSectionsFromSectionItems(v, v);
            }
            visualIndices.resize(sectionItems.count());
            logicalIndices.resize(sectionItems.count());
            int* visual_data = visualIndices.data();
            int* logical_data = logicalIndices.data();
            for (int w = 0; w < sectionItems.count(); ++w) { // Restore visual and logical indexes
                int logindex = sectionItems.at(w).tmpLogIdx;
                if (logindex > logicalFirst)
                    logindex -= changeCount;
                visual_data[logindex] = w;
                logical_data[w] = logindex;
            }
        }
        // ### handle sectionSelection (sectionHidden is handled by updateHiddenSections)
    }

    // update sorting column
    if (sortIndicatorSection >= logicalFirst) {
        if (sortIndicatorSection <= logicalLast)
            sortIndicatorSection = -1;
        else
            sortIndicatorSection -= changeCount;
    }

    // if we only have the last section (the "end" position) left, the header is empty
    if (sectionCount() <= 0)
        clear();
    invalidateCachedSizeHint();
    emit q->sectionCountChanged(oldCount, q->count());

    if (q->stretchLastSection()) {
        const bool lastSectionRemoved = lastSectionLogicalIdx >= logicalFirst && lastSectionLogicalIdx <= logicalLast;
        if (lastSectionRemoved)
            setNewLastSection(lastVisibleVisualIndex());
        else
            lastSectionLogicalIdx = logicalIndex(lastVisibleVisualIndex()); // Just update the last log index.
        doDelayedResizeSections();
    }

    viewport->update();
}

void QHeaderViewPrivate::_q_sectionsAboutToBeChanged()
{
    //if there is no row/column we can't have mapping for columns
    //because no QModelIndex in the model would be valid
    // ### this is far from being bullet-proof and we would need a real system to
    // ### map columns or rows persistently
    if ((orientation == Qt::Horizontal && model->rowCount(root) == 0)
        || model->columnCount(root) == 0)
        return;

    if (hiddenSectionSize.count() == 0)
        return;

    for (int i = 0; i < sectionItems.count(); ++i)
        if (isVisualIndexHidden(i)) // ### note that we are using column or row 0
            persistentHiddenSections.append(orientation == Qt::Horizontal
                                            ? model->index(0, logicalIndex(i), root)
                                            : model->index(logicalIndex(i), 0, root));
}

void QHeaderViewPrivate::_q_sectionsChanged()
{
    Q_Q(QHeaderView);
    viewport->update();

    const auto hiddenSections = persistentHiddenSections;
    persistentHiddenSections.clear();

    clear();
    q->initializeSections();
    invalidateCachedSizeHint();

    if (modelIsEmpty()) {
        return;
    }

    for (const auto &index : hiddenSections) {
        if (index.isValid()) {
            const int logical = (orientation == Qt::Horizontal
                                 ? index.column()
                                 : index.row());
            q->setSectionHidden(logical, true);
        }
    }
}

/*!
  \internal
*/

void QHeaderView::initializeSections()
{
    Q_D(QHeaderView);
    const int oldCount = d->sectionCount();
    const int newCount = d->modelSectionCount();
    if (newCount <= 0) {
            d->clear();
            emit sectionCountChanged(oldCount, 0);
    } else if (newCount != oldCount) {
        const int min = qBound(0, oldCount, newCount - 1);
        initializeSections(min, newCount - 1);
        if (stretchLastSection())   // we've already gotten the size hint
            d->maybeRestorePrevLastSectionAndStretchLast();

        //make sure we update the hidden sections
        if (newCount < oldCount)
            d->updateHiddenSections(0, newCount-1);
    }
}

/*!
    \internal
*/

void QHeaderView::initializeSections(int start, int end)
{
    Q_D(QHeaderView);

    Q_ASSERT(start >= 0);
    Q_ASSERT(end >= 0);

    d->invalidateCachedSizeHint();
    int oldCount = d->sectionCount();

    if (end + 1 < d->sectionCount()) {
        int newCount = end + 1;
        d->removeSectionsFromSectionItems(newCount, d->sectionCount() - 1);
        if (!d->hiddenSectionSize.isEmpty()) {
            if (oldCount - newCount > d->hiddenSectionSize.count()) {
                for (int i = end + 1; i < d->sectionCount(); ++i)
                    d->hiddenSectionSize.remove(i);
            } else {
                QHash<int, int>::iterator it = d->hiddenSectionSize.begin();
                while (it != d->hiddenSectionSize.end()) {
                    if (it.key() > end)
                        it = d->hiddenSectionSize.erase(it);
                    else
                        ++it;
                }
            }
        }
    }

    int newSectionCount = end + 1;

    if (!d->logicalIndices.isEmpty()) {
        if (oldCount <= newSectionCount) {
            d->logicalIndices.resize(newSectionCount);
            d->visualIndices.resize(newSectionCount);
            for (int i = oldCount; i < newSectionCount; ++i) {
                d->logicalIndices[i] = i;
                d->visualIndices[i] = i;
            }
        } else {
            int j = 0;
            for (int i = 0; i < oldCount; ++i) {
                int v = d->logicalIndices.at(i);
                if (v < newSectionCount) {
                    d->logicalIndices[j] = v;
                    d->visualIndices[v] = j;
                    j++;
                }
            }
            d->logicalIndices.resize(newSectionCount);
            d->visualIndices.resize(newSectionCount);
        }
    }

    if (d->globalResizeMode == Stretch)
        d->stretchSections = newSectionCount;
    else if (d->globalResizeMode == ResizeToContents)
         d->contentsSections = newSectionCount;

    if (newSectionCount > oldCount)
        d->createSectionItems(start, end, (end - start + 1) * d->defaultSectionSize, d->globalResizeMode);
    //Q_ASSERT(d->headerLength() == d->length);

    if (d->sectionCount() != oldCount)
        emit sectionCountChanged(oldCount,  d->sectionCount());
    d->viewport->update();
}

/*!
  \reimp
*/

void QHeaderView::currentChanged(const QModelIndex &current, const QModelIndex &old)
{
    Q_D(QHeaderView);

    if (d->orientation == Qt::Horizontal && current.column() != old.column()) {
        if (old.isValid() && old.parent() == d->root)
            d->viewport->update(QRect(sectionViewportPosition(old.column()), 0,
                                    sectionSize(old.column()), d->viewport->height()));
        if (current.isValid() && current.parent() == d->root)
            d->viewport->update(QRect(sectionViewportPosition(current.column()), 0,
                                    sectionSize(current.column()), d->viewport->height()));
    } else if (d->orientation == Qt::Vertical && current.row() != old.row()) {
        if (old.isValid() && old.parent() == d->root)
            d->viewport->update(QRect(0, sectionViewportPosition(old.row()),
                                    d->viewport->width(), sectionSize(old.row())));
        if (current.isValid() && current.parent() == d->root)
            d->viewport->update(QRect(0, sectionViewportPosition(current.row()),
                                    d->viewport->width(), sectionSize(current.row())));
    }
}


/*!
  \reimp
*/

bool QHeaderView::event(QEvent *e)
{
    Q_D(QHeaderView);
    switch (e->type()) {
    case QEvent::HoverEnter: {
        QHoverEvent *he = static_cast<QHoverEvent*>(e);
        d->hover = logicalIndexAt(he->pos());
        if (d->hover != -1)
            updateSection(d->hover);
        break; }
    case QEvent::Leave:
    case QEvent::HoverLeave: {
        if (d->hover != -1)
            updateSection(d->hover);
        d->hover = -1;
        break; }
    case QEvent::HoverMove: {
        QHoverEvent *he = static_cast<QHoverEvent*>(e);
        int oldHover = d->hover;
        d->hover = logicalIndexAt(he->pos());
        if (d->hover != oldHover) {
            if (oldHover != -1)
                updateSection(oldHover);
            if (d->hover != -1)
                updateSection(d->hover);
        }
        break; }
    case QEvent::Timer: {
        QTimerEvent *te = static_cast<QTimerEvent*>(e);
        if (te->timerId() == d->delayedResize.timerId()) {
            d->delayedResize.stop();
            resizeSections();
        }
        break; }
    case QEvent::StyleChange:
        if (!d->customDefaultSectionSize)
            d->updateDefaultSectionSizeFromStyle();
        break;
    default:
        break;
    }
    return QAbstractItemView::event(e);
}

/*!
  \reimp
*/

void QHeaderView::paintEvent(QPaintEvent *e)
{
    Q_D(QHeaderView);

    if (count() == 0)
        return;

    QPainter painter(d->viewport);
    const QPoint offset = d->scrollDelayOffset;
    QRect translatedEventRect = e->rect();
    translatedEventRect.translate(offset);

    int start = -1;
    int end = -1;
    if (d->orientation == Qt::Horizontal) {
        start = visualIndexAt(translatedEventRect.left());
        end = visualIndexAt(translatedEventRect.right());
    } else {
        start = visualIndexAt(translatedEventRect.top());
        end = visualIndexAt(translatedEventRect.bottom());
    }

    if (d->reverse()) {
        start = (start == -1 ? count() - 1 : start);
        end = (end == -1 ? 0 : end);
    } else {
        start = (start == -1 ? 0 : start);
        end = (end == -1 ? count() - 1 : end);
    }

    int tmp = start;
    start = qMin(start, end);
    end = qMax(tmp, end);

    d->prepareSectionSelected(); // clear and resize the bit array

    QRect currentSectionRect;
    int logical;
    const int width = d->viewport->width();
    const int height = d->viewport->height();
    for (int i = start; i <= end; ++i) {
        if (d->isVisualIndexHidden(i))
            continue;
        painter.save();
        logical = logicalIndex(i);
        if (d->orientation == Qt::Horizontal) {
            currentSectionRect.setRect(sectionViewportPosition(logical), 0, sectionSize(logical), height);
        } else {
            currentSectionRect.setRect(0, sectionViewportPosition(logical), width, sectionSize(logical));
        }
        currentSectionRect.translate(offset);

        QVariant variant = d->model->headerData(logical, d->orientation,
                                                Qt::FontRole);
        if (variant.isValid() && variant.canConvert<QFont>()) {
            QFont sectionFont = qvariant_cast<QFont>(variant);
            painter.setFont(sectionFont);
        }
        paintSection(&painter, currentSectionRect, logical);
        painter.restore();
    }

    QStyleOption opt;
    opt.init(this);
    // Paint the area beyond where there are indexes
    if (d->reverse()) {
        opt.state |= QStyle::State_Horizontal;
        if (currentSectionRect.left() > translatedEventRect.left()) {
            opt.rect = QRect(translatedEventRect.left(), 0,
                             currentSectionRect.left() - translatedEventRect.left(), height);
            style()->drawControl(QStyle::CE_HeaderEmptyArea, &opt, &painter, this);
        }
    } else if (currentSectionRect.right() < translatedEventRect.right()) {
        // paint to the right
        opt.state |= QStyle::State_Horizontal;
        opt.rect = QRect(currentSectionRect.right() + 1, 0,
                         translatedEventRect.right() - currentSectionRect.right(), height);
        style()->drawControl(QStyle::CE_HeaderEmptyArea, &opt, &painter, this);
    } else if (currentSectionRect.bottom() < translatedEventRect.bottom()) {
        // paint the bottom section
        opt.state &= ~QStyle::State_Horizontal;
        opt.rect = QRect(0, currentSectionRect.bottom() + 1,
                         width, height - currentSectionRect.bottom() - 1);
        style()->drawControl(QStyle::CE_HeaderEmptyArea, &opt, &painter, this);
    }

#if 0
    // ### visualize sections
    for (int a = 0, i = 0; i < d->sectionItems.count(); ++i) {
        QColor color((i & 4 ? 255 : 0), (i & 2 ? 255 : 0), (i & 1 ? 255 : 0));
        if (d->orientation == Qt::Horizontal)
            painter.fillRect(a - d->offset, 0, d->sectionItems.at(i).size, 4, color);
        else
            painter.fillRect(0, a - d->offset, 4, d->sectionItems.at(i).size, color);
        a += d->sectionItems.at(i).size;
    }

#endif
}

/*!
  \reimp
*/

void QHeaderView::mousePressEvent(QMouseEvent *e)
{
    Q_D(QHeaderView);
    if (d->state != QHeaderViewPrivate::NoState || e->button() != Qt::LeftButton)
        return;
    int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
    int handle = d->sectionHandleAt(pos);
    d->originalSize = -1; // clear the stored original size
    if (handle == -1) {
        d->pressed = logicalIndexAt(pos);
        if (d->clickableSections)
            emit sectionPressed(d->pressed);

        bool acceptMoveSection = d->movableSections;
        if (acceptMoveSection && d->pressed == 0 && !d->allowUserMoveOfSection0)
            acceptMoveSection = false; // Do not allow moving the tree nod

        if (acceptMoveSection) {
            d->section = d->target = d->pressed;
            if (d->section == -1)
                return;
            d->state = QHeaderViewPrivate::MoveSection;
            d->setupSectionIndicator(d->section, pos);
        } else if (d->clickableSections && d->pressed != -1) {
            updateSection(d->pressed);
            d->state = QHeaderViewPrivate::SelectSections;
        }
    } else if (sectionResizeMode(handle) == Interactive) {
        d->originalSize = sectionSize(handle);
        d->state = QHeaderViewPrivate::ResizeSection;
        d->section = handle;
        d->preventCursorChangeInSetOffset = false;
    }

    d->firstPos = pos;
    d->lastPos = pos;

    d->clearCascadingSections();
}

/*!
  \reimp
*/

void QHeaderView::mouseMoveEvent(QMouseEvent *e)
{
    Q_D(QHeaderView);
    int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
    if (pos < 0 && d->state != QHeaderViewPrivate::SelectSections)
        return;
    if (e->buttons() == Qt::NoButton) {
#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
        // Under Cocoa, when the mouse button is released, may include an extra
        // simulated mouse moved event. The state of the buttons when this event
        // is generated is already "no button" and the code below gets executed
        // just before the mouseReleaseEvent and resets the state. This prevents
        // column dragging from working. So this code is disabled under Cocoa.
        d->state = QHeaderViewPrivate::NoState;
        d->pressed = -1;
#endif
    }
    switch (d->state) {
        case QHeaderViewPrivate::ResizeSection: {
            Q_ASSERT(d->originalSize != -1);
            if (d->cascadingResizing) {
                int delta = d->reverse() ? d->lastPos - pos : pos - d->lastPos;
                int visual = visualIndex(d->section);
                d->cascadingResize(visual, d->headerSectionSize(visual) + delta);
            } else {
                int delta = d->reverse() ? d->firstPos - pos : pos - d->firstPos;
                int newsize = qBound(minimumSectionSize(), d->originalSize + delta, maximumSectionSize());
                resizeSection(d->section, newsize);
            }
            d->lastPos = pos;
            return;
        }
        case QHeaderViewPrivate::MoveSection: {
            if (d->shouldAutoScroll(e->pos()))
                d->startAutoScroll();
            if (qAbs(pos - d->firstPos) >= QApplication::startDragDistance()
#if QT_CONFIG(label)
                || !d->sectionIndicator->isHidden()
#endif
                ) {
                int visual = visualIndexAt(pos);
                if (visual == -1)
                    return;
                if (visual == 0 && logicalIndex(0) == 0 && !d->allowUserMoveOfSection0)
                    return;

                int posThreshold = d->headerSectionPosition(visual) - d->offset + d->headerSectionSize(visual) / 2;
                int moving = visualIndex(d->section);
                if (visual < moving) {
                    if (pos < posThreshold)
                        d->target = d->logicalIndex(visual);
                    else
                        d->target = d->logicalIndex(visual + 1);
                } else if (visual > moving) {
                    if (pos > posThreshold)
                        d->target = d->logicalIndex(visual);
                    else
                        d->target = d->logicalIndex(visual - 1);
                } else {
                    d->target = d->section;
                }
                d->updateSectionIndicator(d->section, pos);
            }
            return;
        }
        case QHeaderViewPrivate::SelectSections: {
            int logical = logicalIndexAt(qMax(-d->offset, pos));
            if (logical == -1 && pos > 0)
                logical = logicalIndex(d->lastVisibleVisualIndex());
            if (logical == d->pressed)
                return; // nothing to do
            else if (d->pressed != -1)
                updateSection(d->pressed);
            d->pressed = logical;
            if (d->clickableSections && logical != -1) {
                emit sectionEntered(d->pressed);
                updateSection(d->pressed);
            }
            return;
        }
        case QHeaderViewPrivate::NoState: {
#ifndef QT_NO_CURSOR
            int handle = d->sectionHandleAt(pos);
            bool hasCursor = testAttribute(Qt::WA_SetCursor);
            if (handle != -1 && (sectionResizeMode(handle) == Interactive)) {
                if (!hasCursor)
                    setCursor(d->orientation == Qt::Horizontal ? Qt::SplitHCursor : Qt::SplitVCursor);
            } else {
                if (hasCursor)
                    unsetCursor();
#ifndef QT_NO_STATUSTIP
                int logical = logicalIndexAt(pos);
                QString statusTip;
                if (logical != -1)
                    statusTip = d->model->headerData(logical, d->orientation, Qt::StatusTipRole).toString();
                if (d->shouldClearStatusTip || !statusTip.isEmpty()) {
                    QStatusTipEvent tip(statusTip);
                    QCoreApplication::sendEvent(d->parent, &tip);
                    d->shouldClearStatusTip = !statusTip.isEmpty();
                }
#endif // !QT_NO_STATUSTIP
            }
#endif
            return;
        }
        default:
            break;
    }
}

/*!
  \reimp
*/

void QHeaderView::mouseReleaseEvent(QMouseEvent *e)
{
    Q_D(QHeaderView);
    int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
    switch (d->state) {
    case QHeaderViewPrivate::MoveSection:
        if (true
#if QT_CONFIG(label)
            && !d->sectionIndicator->isHidden()
#endif
      ) { // moving
            int from = visualIndex(d->section);
            Q_ASSERT(from != -1);
            int to = visualIndex(d->target);
            Q_ASSERT(to != -1);
            moveSection(from, to);
            d->section = d->target = -1;
            d->updateSectionIndicator(d->section, pos);
            break;
        } // not moving
        Q_FALLTHROUGH();
    case QHeaderViewPrivate::SelectSections:
        if (!d->clickableSections) {
            int section = logicalIndexAt(pos);
            updateSection(section);
        }
        Q_FALLTHROUGH();
    case QHeaderViewPrivate::NoState:
        if (d->clickableSections) {
            int section = logicalIndexAt(pos);
            if (section != -1 && section == d->pressed) {
                d->flipSortIndicator(section);
                emit sectionClicked(section);
            }
            if (d->pressed != -1)
                updateSection(d->pressed);
        }
        break;
    case QHeaderViewPrivate::ResizeSection:
        d->originalSize = -1;
        d->clearCascadingSections();
        break;
    default:
        break;
    }
    d->state = QHeaderViewPrivate::NoState;
    d->pressed = -1;
}

/*!
  \reimp
*/

void QHeaderView::mouseDoubleClickEvent(QMouseEvent *e)
{
    Q_D(QHeaderView);
    int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
    int handle = d->sectionHandleAt(pos);
    if (handle > -1 && sectionResizeMode(handle) == Interactive) {
        emit sectionHandleDoubleClicked(handle);
#ifndef QT_NO_CURSOR
        Qt::CursorShape splitCursor = (d->orientation == Qt::Horizontal)
                                      ? Qt::SplitHCursor : Qt::SplitVCursor;
        if (cursor().shape() == splitCursor) {
            // signal handlers may have changed the section size
            handle = d->sectionHandleAt(pos);
            if (!(handle > -1 && sectionResizeMode(handle) == Interactive))
                setCursor(Qt::ArrowCursor);
        }
#endif
    } else {
        emit sectionDoubleClicked(logicalIndexAt(e->pos()));
    }
}

/*!
  \reimp
*/

bool QHeaderView::viewportEvent(QEvent *e)
{
    Q_D(QHeaderView);
    switch (e->type()) {
#ifndef QT_NO_TOOLTIP
    case QEvent::ToolTip: {
        QHelpEvent *he = static_cast<QHelpEvent*>(e);
        int logical = logicalIndexAt(he->pos());
        if (logical != -1) {
            QVariant variant = d->model->headerData(logical, d->orientation, Qt::ToolTipRole);
            if (variant.isValid()) {
                QToolTip::showText(he->globalPos(), variant.toString(), this);
                return true;
            }
        }
        break; }
#endif
#if QT_CONFIG(whatsthis)
    case QEvent::QueryWhatsThis: {
        QHelpEvent *he = static_cast<QHelpEvent*>(e);
        int logical = logicalIndexAt(he->pos());
        if (logical != -1
            && d->model->headerData(logical, d->orientation, Qt::WhatsThisRole).isValid())
            return true;
        break; }
    case QEvent::WhatsThis: {
        QHelpEvent *he = static_cast<QHelpEvent*>(e);
        int logical = logicalIndexAt(he->pos());
        if (logical != -1) {
             QVariant whatsthis = d->model->headerData(logical, d->orientation,
                                                      Qt::WhatsThisRole);
             if (whatsthis.isValid()) {
                 QWhatsThis::showText(he->globalPos(), whatsthis.toString(), this);
                 return true;
             }
        }
        break; }
#endif // QT_CONFIG(whatsthis)
#if QT_CONFIG(statustip)
    case QEvent::StatusTip: {
        QHelpEvent *he = static_cast<QHelpEvent*>(e);
        int logical = logicalIndexAt(he->pos());
        if (logical != -1) {
            QString statustip = d->model->headerData(logical, d->orientation,
                                                    Qt::StatusTipRole).toString();
            if (!statustip.isEmpty())
                setStatusTip(statustip);
        }
        return true; }
#endif // QT_CONFIG(statustip)
    case QEvent::FontChange:
    case QEvent::StyleChange:
        d->invalidateCachedSizeHint();
        Q_FALLTHROUGH();
    case QEvent::Hide:
    case QEvent::Show: {
        QAbstractScrollArea *parent = qobject_cast<QAbstractScrollArea *>(parentWidget());
        if (parent && parent->isVisible()) // Only resize if we have a visible parent
            resizeSections();
        emit geometriesChanged();
        break;}
    case QEvent::ContextMenu: {
        d->state = QHeaderViewPrivate::NoState;
        d->pressed = d->section = d->target = -1;
        d->updateSectionIndicator(d->section, -1);
        break; }
    case QEvent::Wheel: {
        QAbstractScrollArea *asa = qobject_cast<QAbstractScrollArea *>(parentWidget());
        if (asa)
            return QApplication::sendEvent(asa->viewport(), e);
        break; }
    default:
        break;
    }
    return QAbstractItemView::viewportEvent(e);
}

/*!
    Paints the section specified by the given \a logicalIndex, using the given
    \a painter and \a rect.

    Normally, you do not have to call this function.
*/

void QHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
    Q_D(const QHeaderView);
    if (!rect.isValid())
        return;
    // get the state of the section
    QStyleOptionHeader opt;
    initStyleOption(&opt);
    QStyle::State state = QStyle::State_None;
    if (isEnabled())
        state |= QStyle::State_Enabled;
    if (window()->isActiveWindow())
        state |= QStyle::State_Active;
    if (d->clickableSections) {
        if (logicalIndex == d->hover)
            state |= QStyle::State_MouseOver;
        if (logicalIndex == d->pressed)
            state |= QStyle::State_Sunken;
        else if (d->highlightSelected) {
            if (d->sectionIntersectsSelection(logicalIndex))
                state |= QStyle::State_On;
            if (d->isSectionSelected(logicalIndex))
                state |= QStyle::State_Sunken;
        }

    }
    if (isSortIndicatorShown() && sortIndicatorSection() == logicalIndex)
        opt.sortIndicator = (sortIndicatorOrder() == Qt::AscendingOrder)
                            ? QStyleOptionHeader::SortDown : QStyleOptionHeader::SortUp;

    // setup the style options structure
    QVariant textAlignment = d->model->headerData(logicalIndex, d->orientation,
                                                  Qt::TextAlignmentRole);
    opt.rect = rect;
    opt.section = logicalIndex;
    opt.state |= state;
    opt.textAlignment = Qt::Alignment(textAlignment.isValid()
                                      ? Qt::Alignment(textAlignment.toInt())
                                      : d->defaultAlignment);

    opt.iconAlignment = Qt::AlignVCenter;
    opt.text = d->model->headerData(logicalIndex, d->orientation,
                                    Qt::DisplayRole).toString();

    int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, 0, this);

    const Qt::Alignment headerArrowAlignment = static_cast<Qt::Alignment>(style()->styleHint(QStyle::SH_Header_ArrowAlignment, 0, this));
    const bool isHeaderArrowOnTheSide = headerArrowAlignment & Qt::AlignVCenter;
    if (isSortIndicatorShown() && sortIndicatorSection() == logicalIndex && isHeaderArrowOnTheSide)
        margin += style()->pixelMetric(QStyle::PM_HeaderMarkSize, 0, this);

    if (d->textElideMode != Qt::ElideNone)
        opt.text = opt.fontMetrics.elidedText(opt.text, d->textElideMode , rect.width() - margin);

    QVariant variant = d->model->headerData(logicalIndex, d->orientation,
                                    Qt::DecorationRole);
    opt.icon = qvariant_cast<QIcon>(variant);
    if (opt.icon.isNull())
        opt.icon = qvariant_cast<QPixmap>(variant);
    QVariant foregroundBrush = d->model->headerData(logicalIndex, d->orientation,
                                                    Qt::ForegroundRole);
    if (foregroundBrush.canConvert<QBrush>())
        opt.palette.setBrush(QPalette::ButtonText, qvariant_cast<QBrush>(foregroundBrush));

    QPointF oldBO = painter->brushOrigin();
    QVariant backgroundBrush = d->model->headerData(logicalIndex, d->orientation,
                                                    Qt::BackgroundRole);
    if (backgroundBrush.canConvert<QBrush>()) {
        opt.palette.setBrush(QPalette::Button, qvariant_cast<QBrush>(backgroundBrush));
        opt.palette.setBrush(QPalette::Window, qvariant_cast<QBrush>(backgroundBrush));
        painter->setBrushOrigin(opt.rect.topLeft());
    }

    // the section position
    int visual = visualIndex(logicalIndex);
    Q_ASSERT(visual != -1);
    bool first = d->isFirstVisibleSection(visual);
    bool last = d->isLastVisibleSection(visual);
    if (first && last)
        opt.position = QStyleOptionHeader::OnlyOneSection;
    else if (first)
        opt.position = QStyleOptionHeader::Beginning;
    else if (last)
        opt.position = QStyleOptionHeader::End;
    else
        opt.position = QStyleOptionHeader::Middle;
    opt.orientation = d->orientation;
    // the selected position
    bool previousSelected = d->isSectionSelected(this->logicalIndex(visual - 1));
    bool nextSelected =  d->isSectionSelected(this->logicalIndex(visual + 1));
    if (previousSelected && nextSelected)
        opt.selectedPosition = QStyleOptionHeader::NextAndPreviousAreSelected;
    else if (previousSelected)
        opt.selectedPosition = QStyleOptionHeader::PreviousIsSelected;
    else if (nextSelected)
        opt.selectedPosition = QStyleOptionHeader::NextIsSelected;
    else
        opt.selectedPosition = QStyleOptionHeader::NotAdjacent;
    // draw the section
    style()->drawControl(QStyle::CE_Header, &opt, painter, this);

    painter->setBrushOrigin(oldBO);
}

/*!
    Returns the size of the contents of the section specified by the given
    \a logicalIndex.

    \sa defaultSectionSize()
*/

QSize QHeaderView::sectionSizeFromContents(int logicalIndex) const
{
    Q_D(const QHeaderView);
    Q_ASSERT(logicalIndex >= 0);

    ensurePolished();

    // use SizeHintRole
    QVariant variant = d->model->headerData(logicalIndex, d->orientation, Qt::SizeHintRole);
    if (variant.isValid())
        return qvariant_cast<QSize>(variant);

    // otherwise use the contents
    QStyleOptionHeader opt;
    initStyleOption(&opt);
    opt.section = logicalIndex;
    QVariant var = d->model->headerData(logicalIndex, d->orientation,
                                            Qt::FontRole);
    QFont fnt;
    if (var.isValid() && var.canConvert<QFont>())
        fnt = qvariant_cast<QFont>(var);
    else
        fnt = font();
    fnt.setBold(true);
    opt.fontMetrics = QFontMetrics(fnt);
    opt.text = d->model->headerData(logicalIndex, d->orientation,
                                    Qt::DisplayRole).toString();
    variant = d->model->headerData(logicalIndex, d->orientation, Qt::DecorationRole);
    opt.icon = qvariant_cast<QIcon>(variant);
    if (opt.icon.isNull())
        opt.icon = qvariant_cast<QPixmap>(variant);
    if (isSortIndicatorShown())
        opt.sortIndicator = QStyleOptionHeader::SortDown;
    return style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), this);
}

/*!
    Returns the horizontal offset of the header. This is 0 for vertical
    headers.

    \sa offset()
*/

int QHeaderView::horizontalOffset() const
{
    Q_D(const QHeaderView);
    if (d->orientation == Qt::Horizontal)
        return d->offset;
    return 0;
}

/*!
    Returns the vertical offset of the header. This is 0 for horizontal
    headers.

    \sa offset()
*/

int QHeaderView::verticalOffset() const
{
    Q_D(const QHeaderView);
    if (d->orientation == Qt::Vertical)
        return d->offset;
    return 0;
}

/*!
    \reimp
    \internal
*/

void QHeaderView::updateGeometries()
{
    Q_D(QHeaderView);
    d->layoutChildren();
    if (d->hasAutoResizeSections())
        d->doDelayedResizeSections();
}

/*!
    \reimp
    \internal
*/

void QHeaderView::scrollContentsBy(int dx, int dy)
{
    Q_D(QHeaderView);
    d->scrollDirtyRegion(dx, dy);
}

/*!
    \reimp
    \internal
*/
void QHeaderView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &)
{
    Q_D(QHeaderView);
    d->invalidateCachedSizeHint();
    if (d->hasAutoResizeSections()) {
        bool resizeRequired = d->globalResizeMode == ResizeToContents;
        int first = orientation() == Qt::Horizontal ? topLeft.column() : topLeft.row();
        int last = orientation() == Qt::Horizontal ? bottomRight.column() : bottomRight.row();
        for (int i = first; i <= last && !resizeRequired; ++i)
            resizeRequired = (sectionResizeMode(i) == ResizeToContents);
        if (resizeRequired)
            d->doDelayedResizeSections();
    }
}

/*!
    \reimp
    \internal

    Empty implementation because the header doesn't show QModelIndex items.
*/
void QHeaderView::rowsInserted(const QModelIndex &, int, int)
{
    // do nothing
}

/*!
    \reimp
    \internal

    Empty implementation because the header doesn't show QModelIndex items.
*/

QRect QHeaderView::visualRect(const QModelIndex &) const
{
    return QRect();
}

/*!
    \reimp
    \internal

    Empty implementation because the header doesn't show QModelIndex items.
*/

void QHeaderView::scrollTo(const QModelIndex &, ScrollHint)
{
    // do nothing - the header only displays sections
}

/*!
    \reimp
    \internal

    Empty implementation because the header doesn't show QModelIndex items.
*/

QModelIndex QHeaderView::indexAt(const QPoint &) const
{
    return QModelIndex();
}

/*!
    \reimp
    \internal

    Empty implementation because the header doesn't show QModelIndex items.
*/

bool QHeaderView::isIndexHidden(const QModelIndex &) const
{
    return true; // the header view has no items, just sections
}

/*!
    \reimp
    \internal

    Empty implementation because the header doesn't show QModelIndex items.
*/

QModelIndex QHeaderView::moveCursor(CursorAction, Qt::KeyboardModifiers)
{
    return QModelIndex();
}

/*!
    \reimp

    Selects the items in the given \a rect according to the specified
    \a flags.

    The base class implementation does nothing.
*/

void QHeaderView::setSelection(const QRect&, QItemSelectionModel::SelectionFlags)
{
    // do nothing
}

/*!
    \internal
*/

QRegion QHeaderView::visualRegionForSelection(const QItemSelection &selection) const
{
    Q_D(const QHeaderView);
    const int max = d->modelSectionCount();

    if (d->orientation == Qt::Horizontal) {
        int logicalLeft = max;
        int logicalRight = 0;

        if (d->visualIndices.empty()) {
            // If no reordered sections, skip redundant visual-to-logical transformations
            for (const auto &r : selection) {
                if (r.parent().isValid() || !r.isValid())
                    continue; // we only know about toplevel items and we don't want invalid ranges
                if (r.left() < logicalLeft)
                    logicalLeft = r.left();
                if (r.right() > logicalRight)
                    logicalRight = r.right();
            }
        } else {
            int left = max;
            int right = 0;
            for (const auto &r : selection) {
                if (r.parent().isValid() || !r.isValid())
                    continue; // we only know about toplevel items and we don't want invalid ranges
                for (int k = r.left(); k <= r.right(); ++k) {
                    int visual = visualIndex(k);
                    if (visual == -1)   // in some cases users may change the selections
                        continue;       // before we have a chance to do the layout
                    if (visual < left)
                        left = visual;
                    if (visual > right)
                        right = visual;
                }
            }
            logicalLeft = logicalIndex(left);
            logicalRight = logicalIndex(right);
        }

        if (logicalLeft < 0  || logicalLeft >= count() ||
            logicalRight < 0 || logicalRight >= count())
            return QRegion();

        int leftPos = sectionViewportPosition(logicalLeft);
        int rightPos = sectionViewportPosition(logicalRight);
        rightPos += sectionSize(logicalRight);
        return QRect(leftPos, 0, rightPos - leftPos, height());
    }
    // orientation() == Qt::Vertical
    int logicalTop = max;
    int logicalBottom = 0;

    if (d->visualIndices.empty()) {
        // If no reordered sections, skip redundant visual-to-logical transformations
        for (const auto &r : selection) {
            if (r.parent().isValid() || !r.isValid())
                continue; // we only know about toplevel items and we don't want invalid ranges
            if (r.top() < logicalTop)
                logicalTop = r.top();
            if (r.bottom() > logicalBottom)
                logicalBottom = r.bottom();
        }
    } else {
        int top = max;
        int bottom = 0;

        for (const auto &r : selection) {
            if (r.parent().isValid() || !r.isValid())
                continue; // we only know about toplevel items and we don't want invalid ranges
            for (int k = r.top(); k <= r.bottom(); ++k) {
                int visual = visualIndex(k);
                if (visual == -1)   // in some cases users may change the selections
                    continue;       // before we have a chance to do the layout
                if (visual < top)
                    top = visual;
                if (visual > bottom)
                    bottom = visual;
            }
        }

        logicalTop = logicalIndex(top);
        logicalBottom = logicalIndex(bottom);
    }

    if (logicalTop < 0 || logicalTop >= count() ||
        logicalBottom < 0 || logicalBottom >= count())
        return QRegion();

    int topPos = sectionViewportPosition(logicalTop);
    int bottomPos = sectionViewportPosition(logicalBottom) + sectionSize(logicalBottom);

    return QRect(0, topPos, width(), bottomPos - topPos);
}


// private implementation

int QHeaderViewPrivate::sectionHandleAt(int position)
{
    Q_Q(QHeaderView);
    int visual = q->visualIndexAt(position);
    if (visual == -1)
        return -1;
    int log = logicalIndex(visual);
    int pos = q->sectionViewportPosition(log);
    int grip = q->style()->pixelMetric(QStyle::PM_HeaderGripMargin, 0, q);

    bool atLeft = position < pos + grip;
    bool atRight = (position > pos + q->sectionSize(log) - grip);
    if (reverse())
        qSwap(atLeft, atRight);

    if (atLeft) {
        //grip at the beginning of the section
        while(visual > -1) {
            int logical = q->logicalIndex(--visual);
            if (!q->isSectionHidden(logical))
                return logical;
        }
    } else if (atRight) {
        //grip at the end of the section
        return log;
    }
    return -1;
}

void QHeaderViewPrivate::setupSectionIndicator(int section, int position)
{
    Q_Q(QHeaderView);
#if QT_CONFIG(label)
    if (!sectionIndicator) {
        sectionIndicator = new QLabel(viewport);
    }
#endif

    int w, h;
    int p = q->sectionViewportPosition(section);
    if (orientation == Qt::Horizontal) {
        w = q->sectionSize(section);
        h = viewport->height();
    } else {
        w = viewport->width();
        h = q->sectionSize(section);
    }
#if QT_CONFIG(label)
    sectionIndicator->resize(w, h);
#endif

    QPixmap pm(w, h);
    pm.fill(QColor(0, 0, 0, 45));
    QRect rect(0, 0, w, h);

    QPainter painter(&pm);
    painter.setOpacity(0.75);
    q->paintSection(&painter, rect, section);
    painter.end();

#if QT_CONFIG(label)
    sectionIndicator->setPixmap(pm);
#endif
    sectionIndicatorOffset = position - qMax(p, 0);
}

void QHeaderViewPrivate::updateSectionIndicator(int section, int position)
{
#if QT_CONFIG(label)
    if (!sectionIndicator)
        return;

    if (section == -1 || target == -1) {
        sectionIndicator->hide();
        return;
    }

    if (orientation == Qt::Horizontal)
        sectionIndicator->move(position - sectionIndicatorOffset, 0);
    else
        sectionIndicator->move(0, position - sectionIndicatorOffset);

    sectionIndicator->show();
#endif
}

/*!
    Initialize \a option with the values from this QHeaderView. This method is
    useful for subclasses when they need a QStyleOptionHeader, but do not want
    to fill in all the information themselves.

    \sa QStyleOption::initFrom()
*/
void QHeaderView::initStyleOption(QStyleOptionHeader *option) const
{
    Q_D(const QHeaderView);
    option->initFrom(this);
    option->state = QStyle::State_None | QStyle::State_Raised;
    option->orientation = d->orientation;
    if (d->orientation == Qt::Horizontal)
        option->state |= QStyle::State_Horizontal;
    if (isEnabled())
        option->state |= QStyle::State_Enabled;
    option->section = 0;
}

bool QHeaderViewPrivate::isSectionSelected(int section) const
{
    int i = section * 2;
    if (i < 0 || i >= sectionSelected.count())
        return false;
    if (sectionSelected.testBit(i)) // if the value was cached
        return sectionSelected.testBit(i + 1);
    bool s = false;
    if (orientation == Qt::Horizontal)
        s = isColumnSelected(section);
    else
        s = isRowSelected(section);
    sectionSelected.setBit(i + 1, s); // selection state
    sectionSelected.setBit(i, true); // cache state
    return s;
}

bool QHeaderViewPrivate::isFirstVisibleSection(int section) const
{
    if (sectionStartposRecalc)
        recalcSectionStartPos();
    const SectionItem &item = sectionItems.at(section);
    return item.size > 0 && item.calculated_startpos == 0;
}

bool QHeaderViewPrivate::isLastVisibleSection(int section) const
{
    if (sectionStartposRecalc)
        recalcSectionStartPos();
    const SectionItem &item = sectionItems.at(section);
    return item.size > 0 && item.calculatedEndPos() == length;
}

/*!
    \internal
    Returns the last visible (ie. not hidden) visual index
*/
int QHeaderViewPrivate::lastVisibleVisualIndex() const
{
    Q_Q(const QHeaderView);
    for (int visual = q->count()-1; visual >= 0; --visual) {
        if (!q->isSectionHidden(q->logicalIndex(visual)))
            return visual;
    }

    //default value if no section is actually visible
    return -1;
}

void QHeaderViewPrivate::restoreSizeOnPrevLastSection()
{
    Q_Q(QHeaderView);
    if (lastSectionLogicalIdx < 0)
        return;
    int resizeLogIdx = lastSectionLogicalIdx;
    lastSectionLogicalIdx = -1; // We do not want resize to catch it as the last section.
    q->resizeSection(resizeLogIdx, lastSectionSize);
}

void QHeaderViewPrivate::setNewLastSection(int visualIndexForLastSection)
{
    Q_Q(QHeaderView);
    lastSectionSize = -1;
    lastSectionLogicalIdx = q->logicalIndex(visualIndexForLastSection);
    lastSectionSize = headerSectionSize(visualIndexForLastSection); // pick size directly since ...
    //  q->sectionSize(lastSectionLogicalIdx) may do delayed resize and stretch it before we get the value.
}

void QHeaderViewPrivate::maybeRestorePrevLastSectionAndStretchLast()
{
    Q_Q(const QHeaderView);
    if (!q->stretchLastSection())
        return;

    int nowLastVisualSection = lastVisibleVisualIndex();
    if (lastSectionLogicalIdx == q->logicalIndex(nowLastVisualSection))
        return;

    // restore old last section.
    restoreSizeOnPrevLastSection();
    setNewLastSection(nowLastVisualSection);
    doDelayedResizeSections(); // Do stretch of last section soon (but not now).
}


/*!
    \internal
    Go through and resize all of the sections applying stretchLastSection,
    manual stretches, sizes, and useGlobalMode.

    The different resize modes are:
    Interactive - the user decides the size
    Stretch - take up whatever space is left
    Fixed - the size is set programmatically outside the header
    ResizeToContentes - the size is set based on the contents of the row or column in the parent view

    The resize mode will not affect the last section if stretchLastSection is true.
*/
void QHeaderViewPrivate::resizeSections(QHeaderView::ResizeMode globalMode, bool useGlobalMode)
{
    Q_Q(QHeaderView);
    //stop the timer in case it is delayed
    delayedResize.stop();

    executePostedLayout();
    if (sectionCount() == 0)
        return;

    if (resizeRecursionBlock)
        return;
    resizeRecursionBlock = true;

    invalidateCachedSizeHint();
    const int lastSectionVisualIdx = q->visualIndex(lastSectionLogicalIdx);

    // find stretchLastSection if we have it
    int stretchSection = -1;
    if (stretchLastSection && !useGlobalMode)
        stretchSection = lastSectionVisualIdx;

    // count up the number of stretched sections and how much space left for them
    int lengthToStretch = (orientation == Qt::Horizontal ? viewport->width() : viewport->height());
    int numberOfStretchedSections = 0;
    QList<int> section_sizes;
    for (int i = 0; i < sectionCount(); ++i) {
        if (isVisualIndexHidden(i))
            continue;

        QHeaderView::ResizeMode resizeMode;
        if (useGlobalMode && (i != stretchSection))
            resizeMode = globalMode;
        else
            resizeMode = (i == stretchSection ? QHeaderView::Stretch : headerSectionResizeMode(i));

        if (resizeMode == QHeaderView::Stretch) {
            ++numberOfStretchedSections;
            section_sizes.append(headerSectionSize(i));
            continue;
        }

        // because it isn't stretch, determine its width and remove that from lengthToStretch
        int sectionSize = 0;
        if (resizeMode == QHeaderView::Interactive || resizeMode == QHeaderView::Fixed) {
            sectionSize = qBound(q->minimumSectionSize(), headerSectionSize(i), q->maximumSectionSize());
        } else { // resizeMode == QHeaderView::ResizeToContents
            int logicalIndex = q->logicalIndex(i);
            sectionSize = qMax(viewSectionSizeHint(logicalIndex),
                               q->sectionSizeHint(logicalIndex));
            if (sectionSize > q->maximumSectionSize())
                sectionSize = q->maximumSectionSize();
        }
        section_sizes.append(sectionSize);
        lengthToStretch -= sectionSize;
    }

    // calculate the new length for all of the stretched sections
    int stretchSectionLength = -1;
    int pixelReminder = 0;
    if (numberOfStretchedSections > 0 && lengthToStretch > 0) { // we have room to stretch in
        int hintLengthForEveryStretchedSection = lengthToStretch / numberOfStretchedSections;
        stretchSectionLength = qMax(hintLengthForEveryStretchedSection, q->minimumSectionSize());
        pixelReminder = lengthToStretch % numberOfStretchedSections;
    }

    // ### The code below would be nicer if it was cleaned up a bit (since spans has been replaced with items)
    int spanStartSection = 0;
    int previousSectionLength = 0;

    QHeaderView::ResizeMode previousSectionResizeMode = QHeaderView::Interactive;

    // resize each section along the total length
    for (int i = 0; i < sectionCount(); ++i) {
        int oldSectionLength = headerSectionSize(i);
        int newSectionLength = -1;
        QHeaderView::ResizeMode newSectionResizeMode = headerSectionResizeMode(i);

        if (isVisualIndexHidden(i)) {
            newSectionLength = 0;
        } else {
            QHeaderView::ResizeMode resizeMode;
            if (useGlobalMode)
                resizeMode = globalMode;
            else
                resizeMode = (i == stretchSection
                              ? QHeaderView::Stretch
                              : newSectionResizeMode);
            if (resizeMode == QHeaderView::Stretch && stretchSectionLength != -1) {
                if (i == lastSectionVisualIdx)
                    newSectionLength = qMax(stretchSectionLength, lastSectionSize);
                else
                    newSectionLength = stretchSectionLength;
                if (pixelReminder > 0) {
                    newSectionLength += 1;
                    --pixelReminder;
                }
                section_sizes.removeFirst();
            } else {
                newSectionLength = section_sizes.takeFirst();
            }
        }

        //Q_ASSERT(newSectionLength > 0);
        if ((previousSectionResizeMode != newSectionResizeMode
            || previousSectionLength != newSectionLength) && i > 0) {
            int spanLength = (i - spanStartSection) * previousSectionLength;
            createSectionItems(spanStartSection, i - 1, spanLength, previousSectionResizeMode);
            //Q_ASSERT(headerLength() == length);
            spanStartSection = i;
        }

        if (newSectionLength != oldSectionLength)
            emit q->sectionResized(logicalIndex(i), oldSectionLength, newSectionLength);

        previousSectionLength = newSectionLength;
        previousSectionResizeMode = newSectionResizeMode;
    }

    createSectionItems(spanStartSection, sectionCount() - 1,
                      (sectionCount() - spanStartSection) * previousSectionLength,
                      previousSectionResizeMode);
    //Q_ASSERT(headerLength() == length);
    resizeRecursionBlock = false;
    viewport->update();
}

void QHeaderViewPrivate::createSectionItems(int start, int end, int size, QHeaderView::ResizeMode mode)
{
    int sizePerSection = size / (end - start + 1);
    if (end >= sectionItems.count()) {
        sectionItems.resize(end + 1);
        sectionStartposRecalc = true;
    }
    SectionItem *sectiondata = sectionItems.data();
    for (int i = start; i <= end; ++i) {
        length += (sizePerSection - sectiondata[i].size);
        sectionStartposRecalc |= (sectiondata[i].size != sizePerSection);
        sectiondata[i].size = sizePerSection;
        sectiondata[i].resizeMode = mode;
    }
}

void QHeaderViewPrivate::removeSectionsFromSectionItems(int start, int end)
{
    // remove sections
    sectionStartposRecalc |= (end != sectionItems.count() - 1);
    int removedlength = 0;
    for (int u = start; u <= end; ++u)
        removedlength += sectionItems.at(u).size;
    length -= removedlength;
    sectionItems.remove(start, end - start + 1);
}

void QHeaderViewPrivate::clear()
{
    if (state != NoClear) {
    length = 0;
    visualIndices.clear();
    logicalIndices.clear();
    sectionSelected.clear();
    hiddenSectionSize.clear();
    sectionItems.clear();
    lastSectionLogicalIdx = -1;
    invalidateCachedSizeHint();
    }
}

void QHeaderViewPrivate::flipSortIndicator(int section)
{
    Q_Q(QHeaderView);
    Qt::SortOrder sortOrder;
    if (sortIndicatorSection == section) {
        sortOrder = (sortIndicatorOrder == Qt::DescendingOrder) ? Qt::AscendingOrder : Qt::DescendingOrder;
    } else {
        const QVariant value = model->headerData(section, orientation, Qt::InitialSortOrderRole);
        if (value.canConvert(QVariant::Int))
            sortOrder = static_cast<Qt::SortOrder>(value.toInt());
        else
            sortOrder = Qt::AscendingOrder;
    }
    q->setSortIndicator(section, sortOrder);
}

void QHeaderViewPrivate::cascadingResize(int visual, int newSize)
{
    Q_Q(QHeaderView);
    const int minimumSize = q->minimumSectionSize();
    const int oldSize = headerSectionSize(visual);
    int delta = newSize - oldSize;

    if (delta > 0) { // larger
        bool sectionResized = false;

        // restore old section sizes
        for (int i = firstCascadingSection; i < visual; ++i) {
            if (cascadingSectionSize.contains(i)) {
                int currentSectionSize = headerSectionSize(i);
                int originalSectionSize = cascadingSectionSize.value(i);
                if (currentSectionSize < originalSectionSize) {
                    int newSectionSize = currentSectionSize + delta;
                    resizeSectionItem(i, currentSectionSize, newSectionSize);
                    if (newSectionSize >= originalSectionSize && false)
                        cascadingSectionSize.remove(i); // the section is now restored
                    sectionResized = true;
                    break;
                }
            }

        }

        // resize the section
        if (!sectionResized) {
            newSize = qMax(newSize, minimumSize);
            if (oldSize != newSize)
                resizeSectionItem(visual, oldSize, newSize);
        }

        // cascade the section size change
        for (int i = visual + 1; i < sectionCount(); ++i) {
            if (isVisualIndexHidden(i))
                continue;
            if (!sectionIsCascadable(i))
                continue;
            int currentSectionSize = headerSectionSize(i);
            if (currentSectionSize <= minimumSize)
                continue;
            int newSectionSize = qMax(currentSectionSize - delta, minimumSize);
            //qDebug() << "### cascading to" << i << newSectionSize - currentSectionSize << delta;
            resizeSectionItem(i, currentSectionSize, newSectionSize);
            saveCascadingSectionSize(i, currentSectionSize);
            delta = delta - (currentSectionSize - newSectionSize);
            //qDebug() << "new delta" << delta;
            //if (newSectionSize != minimumSize)
            if (delta <= 0)
                break;
        }
    } else { // smaller
        bool sectionResized = false;

        // restore old section sizes
        for (int i = lastCascadingSection; i > visual; --i) {
            if (!cascadingSectionSize.contains(i))
                continue;
            int currentSectionSize = headerSectionSize(i);
            int originalSectionSize = cascadingSectionSize.value(i);
            if (currentSectionSize >= originalSectionSize)
                continue;
            int newSectionSize = currentSectionSize - delta;
            resizeSectionItem(i, currentSectionSize, newSectionSize);
            if (newSectionSize >= originalSectionSize && false) {
                //qDebug() << "section" << i << "restored to" << originalSectionSize;
                cascadingSectionSize.remove(i); // the section is now restored
            }
            sectionResized = true;
            break;
        }

        // resize the section
        resizeSectionItem(visual, oldSize, qMax(newSize, minimumSize));

        // cascade the section size change
        if (delta < 0 && newSize < minimumSize) {
            for (int i = visual - 1; i >= 0; --i) {
                if (isVisualIndexHidden(i))
                    continue;
                if (!sectionIsCascadable(i))
                    continue;
                int sectionSize = headerSectionSize(i);
                if (sectionSize <= minimumSize)
                    continue;
                resizeSectionItem(i, sectionSize, qMax(sectionSize + delta, minimumSize));
                saveCascadingSectionSize(i, sectionSize);
                break;
            }
        }

        // let the next section get the space from the resized section
        if (!sectionResized) {
            for (int i = visual + 1; i < sectionCount(); ++i) {
                if (isVisualIndexHidden(i))
                    continue;
                if (!sectionIsCascadable(i))
                    continue;
                int currentSectionSize = headerSectionSize(i);
                int newSectionSize = qMax(currentSectionSize - delta, minimumSize);
                resizeSectionItem(i, currentSectionSize, newSectionSize);
                break;
            }
        }
    }

    if (hasAutoResizeSections())
        doDelayedResizeSections();

    viewport->update();
}

void QHeaderViewPrivate::setDefaultSectionSize(int size)
{
    Q_Q(QHeaderView);
    executePostedLayout();
    invalidateCachedSizeHint();
    defaultSectionSize = size;
    customDefaultSectionSize = true;
    if (state == QHeaderViewPrivate::ResizeSection)
        preventCursorChangeInSetOffset = true;
    for (int i = 0; i < sectionItems.count(); ++i) {
        QHeaderViewPrivate::SectionItem &section = sectionItems[i];
        if (hiddenSectionSize.isEmpty() || !isVisualIndexHidden(i)) { // resize on not hidden.
            const int newSize = size;
            if (newSize != section.size) {
                length += newSize - section.size; //the whole length is changed
                const int oldSectionSize = section.sectionSize();
                section.size = size;
                emit q->sectionResized(logicalIndex(i), oldSectionSize, size);
            }
        }
    }
    sectionStartposRecalc = true;
    if (hasAutoResizeSections())
        doDelayedResizeSections();
    viewport->update();
}

void QHeaderViewPrivate::updateDefaultSectionSizeFromStyle()
{
    Q_Q(QHeaderView);
    if (orientation == Qt::Horizontal) {
        defaultSectionSize = q->style()->pixelMetric(QStyle::PM_HeaderDefaultSectionSizeHorizontal, 0, q);
    } else {
        defaultSectionSize = qMax(q->minimumSectionSize(),
                                  q->style()->pixelMetric(QStyle::PM_HeaderDefaultSectionSizeVertical, 0, q));
    }
}

void QHeaderViewPrivate::recalcSectionStartPos() const // linear (but fast)
{
    int pixelpos = 0;
    for (QVector<SectionItem>::const_iterator i = sectionItems.constBegin(); i != sectionItems.constEnd(); ++i) {
        i->calculated_startpos = pixelpos; // write into const mutable
        pixelpos += i->size;
    }
    sectionStartposRecalc = false;
}

void QHeaderViewPrivate::resizeSectionItem(int visualIndex, int oldSize, int newSize)
{
    Q_Q(QHeaderView);
    QHeaderView::ResizeMode mode = headerSectionResizeMode(visualIndex);
    createSectionItems(visualIndex, visualIndex, newSize, mode);
    emit q->sectionResized(logicalIndex(visualIndex), oldSize, newSize);
}

int QHeaderViewPrivate::headerSectionSize(int visual) const
{
    if (visual < sectionCount() && visual >= 0)
        return sectionItems.at(visual).sectionSize();
    return -1;
}

int QHeaderViewPrivate::headerSectionPosition(int visual) const
{
    if (visual < sectionCount() && visual >= 0) {
        if (sectionStartposRecalc)
            recalcSectionStartPos();
        return sectionItems.at(visual).calculated_startpos;
    }
    return -1;
}

int QHeaderViewPrivate::headerVisualIndexAt(int position) const
{
    if (sectionStartposRecalc)
        recalcSectionStartPos();
    int startidx = 0;
    int endidx = sectionItems.count() - 1;
    while (startidx <= endidx) {
        int middle = (endidx + startidx) / 2;
        if (sectionItems.at(middle).calculated_startpos > position) {
            endidx = middle - 1;
        } else {
            if (sectionItems.at(middle).calculatedEndPos() <= position)
                startidx = middle + 1;
            else // we found it.
                return middle;
        }
    }
    return -1;
}

void QHeaderViewPrivate::setHeaderSectionResizeMode(int visual, QHeaderView::ResizeMode mode)
{
    int size = headerSectionSize(visual);
    createSectionItems(visual, visual, size, mode);
}

QHeaderView::ResizeMode QHeaderViewPrivate::headerSectionResizeMode(int visual) const
{
    if (visual < 0 || visual >= sectionItems.count())
        return globalResizeMode;
    return static_cast<QHeaderView::ResizeMode>(sectionItems.at(visual).resizeMode);
}

void QHeaderViewPrivate::setGlobalHeaderResizeMode(QHeaderView::ResizeMode mode)
{
    globalResizeMode = mode;
    for (int i = 0; i < sectionItems.count(); ++i)
        sectionItems[i].resizeMode = mode;
}

int QHeaderViewPrivate::viewSectionSizeHint(int logical) const
{
    if (QAbstractItemView *view = qobject_cast<QAbstractItemView*>(parent)) {
        return (orientation == Qt::Horizontal
                ? view->sizeHintForColumn(logical)
                : view->sizeHintForRow(logical));
    }
    return 0;
}

int QHeaderViewPrivate::adjustedVisualIndex(int visualIndex) const
{
    if (!hiddenSectionSize.isEmpty()) {
        int adjustedVisualIndex = visualIndex;
        int currentVisualIndex = 0;
        for (int i = 0; i < sectionItems.count(); ++i) {
            if (isVisualIndexHidden(i))
                ++adjustedVisualIndex;
            else
                ++currentVisualIndex;
            if (currentVisualIndex >= visualIndex)
                break;
        }
        visualIndex = adjustedVisualIndex;
    }
    return visualIndex;
}

void QHeaderViewPrivate::setScrollOffset(const QScrollBar *scrollBar, QAbstractItemView::ScrollMode scrollMode)
{
    Q_Q(QHeaderView);
    if (scrollMode == QAbstractItemView::ScrollPerItem) {
        if (scrollBar->maximum() > 0 && scrollBar->value() == scrollBar->maximum())
            q->setOffsetToLastSection();
        else
            q->setOffsetToSectionPosition(scrollBar->value());
    } else {
        q->setOffset(scrollBar->value());
    }
}

#ifndef QT_NO_DATASTREAM
void QHeaderViewPrivate::write(QDataStream &out) const
{
    out << int(orientation);
    out << int(sortIndicatorOrder);
    out << sortIndicatorSection;
    out << sortIndicatorShown;

    out << visualIndices;
    out << logicalIndices;

    out << sectionsHiddenToBitVector();
    out << hiddenSectionSize;

    out << length;
    out << sectionCount();
    out << movableSections;
    out << clickableSections;
    out << highlightSelected;
    out << stretchLastSection;
    out << cascadingResizing;
    out << stretchSections;
    out << contentsSections;
    out << defaultSectionSize;
    out << minimumSectionSize;

    out << int(defaultAlignment);
    out << int(globalResizeMode);

    out << sectionItems;
    out << resizeContentsPrecision;
    out << customDefaultSectionSize;
    out << lastSectionSize;
}

bool QHeaderViewPrivate::read(QDataStream &in)
{
    Q_Q(QHeaderView);
    int orient, order, align, global;
    int sortIndicatorSectionIn;
    bool sortIndicatorShownIn;
    int lengthIn;
    QVector<int> visualIndicesIn;
    QVector<int> logicalIndicesIn;
    QHash<int, int> hiddenSectionSizeIn;
    bool movableSectionsIn;
    bool clickableSectionsIn;
    bool highlightSelectedIn;
    bool stretchLastSectionIn;
    bool cascadingResizingIn;
    int stretchSectionsIn;
    int contentsSectionsIn;
    int defaultSectionSizeIn;
    int minimumSectionSizeIn;
    QVector<SectionItem> sectionItemsIn;

    in >> orient;
    in >> order;

    in >> sortIndicatorSectionIn;
    in >> sortIndicatorShownIn;

    in >> visualIndicesIn;
    in >> logicalIndicesIn;

    QBitArray sectionHidden;
    in >> sectionHidden;
    in >> hiddenSectionSizeIn;
    in >> lengthIn;

    int unusedSectionCount; // For compatibility
    in >> unusedSectionCount;

    if (in.status() != QDataStream::Ok || lengthIn < 0)
        return false;

    in >> movableSectionsIn;
    in >> clickableSectionsIn;
    in >> highlightSelectedIn;
    in >> stretchLastSectionIn;
    in >> cascadingResizingIn;
    in >> stretchSectionsIn;
    in >> contentsSectionsIn;
    in >> defaultSectionSizeIn;
    in >> minimumSectionSizeIn;

    in >> align;

    in >> global;

    in >> sectionItemsIn;
    // In Qt4 we had a vector of spans where one span could hold information on more sections.
    // Now we have an itemvector where one items contains information about one section
    // For backward compatibility with Qt4 we do the following
    QVector<SectionItem> newSectionItems;
    for (int u = 0; u < sectionItemsIn.count(); ++u) {
        int count = sectionItemsIn.at(u).tmpDataStreamSectionCount;
        if (count > 0)
            sectionItemsIn[u].size /= count;
        for (int n = 0; n < count; ++n)
            newSectionItems.append(sectionItemsIn[u]);
    }

    int sectionItemsLengthTotal = 0;
    foreach (const SectionItem &section, newSectionItems)
        sectionItemsLengthTotal += section.size;
    if (sectionItemsLengthTotal != lengthIn)
        return false;

    const int currentCount = (orient == Qt::Horizontal ? model->columnCount(root) : model->rowCount(root));
    if (newSectionItems.count() < currentCount) {
        // we have sections not in the saved state, give them default settings
        if (!visualIndicesIn.isEmpty() && !logicalIndicesIn.isEmpty()) {
            for (int i = newSectionItems.count(); i < currentCount; ++i) {
                visualIndicesIn.append(i);
                logicalIndicesIn.append(i);
            }
        }
        const int insertCount = currentCount - newSectionItems.count();
        const int insertLength = defaultSectionSizeIn * insertCount;
        lengthIn += insertLength;
        SectionItem section(defaultSectionSizeIn, globalResizeMode);
        newSectionItems.insert(newSectionItems.count(), insertCount, section); // append
    }

    orientation = static_cast<Qt::Orientation>(orient);
    sortIndicatorOrder = static_cast<Qt::SortOrder>(order);
    sortIndicatorSection = sortIndicatorSectionIn;
    sortIndicatorShown = sortIndicatorShownIn;
    visualIndices = visualIndicesIn;
    logicalIndices = logicalIndicesIn;
    hiddenSectionSize = hiddenSectionSizeIn;
    length = lengthIn;

    movableSections = movableSectionsIn;
    clickableSections = clickableSectionsIn;
    highlightSelected = highlightSelectedIn;
    stretchLastSection = stretchLastSectionIn;
    cascadingResizing = cascadingResizingIn;
    stretchSections = stretchSectionsIn;
    contentsSections = contentsSectionsIn;
    defaultSectionSize = defaultSectionSizeIn;
    minimumSectionSize = minimumSectionSizeIn;

    defaultAlignment = Qt::Alignment(align);
    globalResizeMode = static_cast<QHeaderView::ResizeMode>(global);

    sectionItems = newSectionItems;
    setHiddenSectionsFromBitVector(sectionHidden);
    recalcSectionStartPos();

    int tmpint;
    in >> tmpint;
    if (in.status() == QDataStream::Ok)  // we haven't read past end
        resizeContentsPrecision = tmpint;

    bool tmpbool;
    in >> tmpbool;
    if (in.status() == QDataStream::Ok) {  // we haven't read past end
        customDefaultSectionSize = tmpbool;
        if (!customDefaultSectionSize)
            updateDefaultSectionSizeFromStyle();
    }

    lastSectionSize = -1;
    int inLastSectionSize;
    in >> inLastSectionSize;
    if (in.status() == QDataStream::Ok)
        lastSectionSize = inLastSectionSize;

    lastSectionLogicalIdx = -1;
    if (stretchLastSection) {
        lastSectionLogicalIdx = q->logicalIndex(lastVisibleVisualIndex());
        doDelayedResizeSections();
    }

    return true;
}

#endif // QT_NO_DATASTREAM

QT_END_NAMESPACE

#include "moc_qheaderview.cpp"