summaryrefslogtreecommitdiffstats
path: root/tests/auto/quick/qquicktableview/tst_qquicktableview.cpp
blob: fbe56abda5b22612465807f85758dc9ff502927b (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
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** 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 General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** 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-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtQuickTest/quicktest.h>

#include <QtQuick/qquickview.h>
#include <QtQuick/private/qquicktableview_p.h>
#include <QtQuick/private/qquicktableview_p_p.h>
#include <QtQuick/private/qquickloader_p.h>

#include <QtQml/qqmlengine.h>
#include <QtQml/qqmlcontext.h>
#include <QtQml/qqmlexpression.h>
#include <QtQml/qqmlincubator.h>
#include <QtQmlModels/private/qqmlobjectmodel_p.h>
#include <QtQmlModels/private/qqmllistmodel_p.h>

#include "testmodel.h"

#include "../../shared/util.h"
#include "../shared/viewtestutil.h"
#include "../shared/visualtestutil.h"

using namespace QQuickViewTestUtil;
using namespace QQuickVisualTestUtil;

static const char* kTableViewPropName = "tableView";
static const char* kDelegateObjectName = "tableViewDelegate";
static const char *kDelegatesCreatedCountProp = "delegatesCreatedCount";
static const char *kModelDataBindingProp = "modelDataBinding";

Q_DECLARE_METATYPE(QMarginsF);

#define GET_QML_TABLEVIEW(PROPNAME) \
    auto PROPNAME = view->rootObject()->property(#PROPNAME).value<QQuickTableView *>(); \
    QVERIFY(PROPNAME); \
    auto PROPNAME ## Private = QQuickTableViewPrivate::get(PROPNAME); \
    Q_UNUSED(PROPNAME ## Private)

#define LOAD_TABLEVIEW(fileName) \
    view->setSource(testFileUrl(fileName)); \
    view->show(); \
    QVERIFY(QTest::qWaitForWindowActive(view)); \
    GET_QML_TABLEVIEW(tableView)

#define LOAD_TABLEVIEW_ASYNC(fileName) \
    view->setSource(testFileUrl("asyncloader.qml")); \
    view->show(); \
    QVERIFY(QTest::qWaitForWindowActive(view)); \
    auto loader = view->rootObject()->property("loader").value<QQuickLoader *>(); \
    loader->setSource(QUrl::fromLocalFile("data/" fileName)); \
    QTRY_VERIFY(loader->item()); \
    QCOMPARE(loader->status(), QQuickLoader::Status::Ready); \
    GET_QML_TABLEVIEW(tableView)

#define WAIT_UNTIL_POLISHED_ARG(item) \
    QVERIFY(QQuickTest::qIsPolishScheduled(item)); \
    QVERIFY(QQuickTest::qWaitForItemPolished(item))
#define WAIT_UNTIL_POLISHED WAIT_UNTIL_POLISHED_ARG(tableView)

class tst_QQuickTableView : public QQmlDataTest
{
    Q_OBJECT
public:
    tst_QQuickTableView();

    QQuickTableViewAttached *getAttachedObject(const QObject *object) const;
    QPoint getContextRowAndColumn(const QQuickItem *item) const;

private:
    QQuickView *view = nullptr;

private slots:
    void initTestCase() override;
    void cleanupTestCase();

    void setAndGetModel_data();
    void setAndGetModel();
    void emptyModel_data();
    void emptyModel();
    void checkPreload_data();
    void checkPreload();
    void checkZeroSizedDelegate();
    void checkImplicitSizeDelegate();
    void checkColumnWidthWithoutProvider();
    void checkDelegateWithAnchors();
    void checkColumnWidthProvider();
    void checkColumnWidthProviderInvalidReturnValues();
    void checkColumnWidthProviderNegativeReturnValue();
    void checkColumnWidthProviderNotCallable();
    void checkRowHeightWithoutProvider();
    void checkRowHeightProvider();
    void checkRowHeightProviderInvalidReturnValues();
    void checkRowHeightProviderNegativeReturnValue();
    void checkRowHeightProviderNotCallable();
    void checkForceLayoutFunction();
    void checkContentWidthAndHeight();
    void checkPageFlicking();
    void checkExplicitContentWidthAndHeight();
    void checkExtents_origin();
    void checkExtents_endExtent();
    void checkExtents_moveTableToEdge();
    void checkContentXY();
    void noDelegate();
    void changeDelegateDuringUpdate();
    void changeModelDuringUpdate();
    void countDelegateItems_data();
    void countDelegateItems();
    void checkLayoutOfEqualSizedDelegateItems_data();
    void checkLayoutOfEqualSizedDelegateItems();
    void checkFocusRemoved_data();
    void checkFocusRemoved();
    void fillTableViewButNothingMore_data();
    void fillTableViewButNothingMore();
    void checkInitialAttachedProperties_data();
    void checkInitialAttachedProperties();
    void checkSpacingValues();
    void checkDelegateParent();
    void flick_data();
    void flick();
    void flickOvershoot_data();
    void flickOvershoot();
    void checkRowColumnCount();
    void modelSignals();
    void checkModelSignalsUpdateLayout();
    void dataChangedSignal();
    void checkThatPoolIsDrainedWhenReuseIsFalse();
    void checkIfDelegatesAreReused_data();
    void checkIfDelegatesAreReused();
    void checkIfDelegatesAreReusedAsymmetricTableSize();
    void checkContextProperties_data();
    void checkContextProperties();
    void checkContextPropertiesQQmlListProperyModel_data();
    void checkContextPropertiesQQmlListProperyModel();
    void checkRowAndColumnChangedButNotIndex();
    void checkChangingModelFromDelegate();
    void checkRebuildViewportOnly();
    void useDelegateChooserWithoutDefault();
    void checkTableviewInsideAsyncLoader();
    void hideRowsAndColumns_data();
    void hideRowsAndColumns();
    void checkThatRevisionedPropertiesCannotBeUsedInOldImports();
    void checkSyncView_rootView_data();
    void checkSyncView_rootView();
    void checkSyncView_childViews_data();
    void checkSyncView_childViews();
    void checkSyncView_differentSizedModels();
    void checkSyncView_connect_late_data();
    void checkSyncView_connect_late();
};

tst_QQuickTableView::tst_QQuickTableView()
{
}

void tst_QQuickTableView::initTestCase()
{
    QQmlDataTest::initTestCase();
    qmlRegisterType<TestModel>("TestModel", 0, 1, "TestModel");
    view = createView();
}

void tst_QQuickTableView::cleanupTestCase()
{
    delete view;
}

QQuickTableViewAttached *tst_QQuickTableView::getAttachedObject(const QObject *object) const
{
    QObject *attachedObject = qmlAttachedPropertiesObject<QQuickTableView>(object);
    return static_cast<QQuickTableViewAttached *>(attachedObject);
}

QPoint tst_QQuickTableView::getContextRowAndColumn(const QQuickItem *item) const
{
    const auto context = qmlContext(item);
    const int row = context->contextProperty("row").toInt();
    const int column = context->contextProperty("column").toInt();
    return QPoint(column, row);
}

void tst_QQuickTableView::setAndGetModel_data()
{
    QTest::addColumn<QVariant>("model");

    QTest::newRow("QAIM 1x1") << TestModelAsVariant(1, 1);
    QTest::newRow("Number model 1") << QVariant::fromValue(1);
    QTest::newRow("QStringList 1") << QVariant::fromValue(QStringList() << "one");
}

void tst_QQuickTableView::setAndGetModel()
{
    // Test that we can set and get different kind of models
    QFETCH(QVariant, model);
    LOAD_TABLEVIEW("plaintableview.qml");

    tableView->setModel(model);
    QCOMPARE(model, tableView->model());
}

void tst_QQuickTableView::emptyModel_data()
{
    QTest::addColumn<QVariant>("model");

    QTest::newRow("QAIM") << TestModelAsVariant(0, 0);
    QTest::newRow("Number model") << QVariant::fromValue(0);
    QTest::newRow("QStringList") << QVariant::fromValue(QStringList());
}

void tst_QQuickTableView::emptyModel()
{
    // Check that if we assign an empty model to
    // TableView, no delegate items will be created.
    QFETCH(QVariant, model);
    LOAD_TABLEVIEW("plaintableview.qml");

    tableView->setModel(model);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableViewPrivate->loadedItems.count(), 0);
}

void tst_QQuickTableView::checkPreload_data()
{
    QTest::addColumn<bool>("reuseItems");

    QTest::newRow("reuse") << true;
    QTest::newRow("not reuse") << false;
}

void tst_QQuickTableView::checkPreload()
{
    // Check that the reuse pool is filled up with one extra row and
    // column (pluss corner) after rebuilding the table, but only if we reuse items.
    QFETCH(bool, reuseItems);
    LOAD_TABLEVIEW("plaintableview.qml");

    auto model = TestModelAsVariant(100, 100);
    tableView->setModel(model);
    tableView->setReuseItems(reuseItems);

    WAIT_UNTIL_POLISHED;

    if (reuseItems) {
        const int rowCount = tableViewPrivate->loadedRows.count();
        const int columnCount = tableViewPrivate->loadedColumns.count();
        const int expectedPoolSize = rowCount + columnCount + 1;
        QCOMPARE(tableViewPrivate->tableModel->poolSize(), expectedPoolSize);
    } else {
        QCOMPARE(tableViewPrivate->tableModel->poolSize(), 0);
    }
}

void tst_QQuickTableView::checkZeroSizedDelegate()
{
    // Check that if we assign a delegate with empty width and height, we
    // fall back to use kDefaultColumnWidth and kDefaultRowHeight as
    // column/row sizes.
    LOAD_TABLEVIEW("plaintableview.qml");

    auto model = TestModelAsVariant(100, 100);
    tableView->setModel(model);

    view->rootObject()->setProperty("delegateWidth", 0);
    view->rootObject()->setProperty("delegateHeight", 0);

    QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*implicit"));

    WAIT_UNTIL_POLISHED;

    auto items = tableViewPrivate->loadedItems;
    QVERIFY(!items.isEmpty());

    for (auto fxItem : tableViewPrivate->loadedItems) {
        auto item = fxItem->item;
        QCOMPARE(item->width(), kDefaultColumnWidth);
        QCOMPARE(item->height(), kDefaultRowHeight);
    }
}

void tst_QQuickTableView::checkImplicitSizeDelegate()
{
    // Check that we can set the size of delegate items using
    // implicit width/height, instead of forcing the user to
    // create an attached object by using implicitWidth/Height.
    LOAD_TABLEVIEW("tableviewimplicitsize.qml");

    auto model = TestModelAsVariant(100, 100);
    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    auto items = tableViewPrivate->loadedItems;
    QVERIFY(!items.isEmpty());

    for (auto fxItem : tableViewPrivate->loadedItems) {
        auto item = fxItem->item;
        QCOMPARE(item->width(), 90);
        QCOMPARE(item->height(), 60);
    }
}

void tst_QQuickTableView::checkColumnWidthWithoutProvider()
{
    // Checks that a function isn't assigned to the columnWidthProvider property
    // and that the column width is then equal to sizeHintForColumn.
    LOAD_TABLEVIEW("alternatingrowheightcolumnwidth.qml");

    auto model = TestModelAsVariant(10, 10);

    tableView->setModel(model);
    QVERIFY(tableView->columnWidthProvider().isUndefined());

    WAIT_UNTIL_POLISHED;

    for (const int column : tableViewPrivate->loadedColumns.keys()) {
        const qreal expectedColumnWidth = tableViewPrivate->sizeHintForColumn(column);
        for (const int row : tableViewPrivate->loadedRows.keys()) {
            const auto item = tableViewPrivate->loadedTableItem(QPoint(column, row))->item;
            QCOMPARE(item->width(), expectedColumnWidth);
        }
    }
}

void tst_QQuickTableView::checkDelegateWithAnchors()
{
    // Checks that we issue a warning if the delegate has anchors
    LOAD_TABLEVIEW("delegatewithanchors.qml");

    QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*anchors"));

    auto model = TestModelAsVariant(1, 1);
    tableView->setModel(model);
    WAIT_UNTIL_POLISHED;
}

void tst_QQuickTableView::checkColumnWidthProvider()
{
    // Check that you can assign a function to the columnWidthProvider property, and
    // that it's used to control (and override) the width of the columns.
    LOAD_TABLEVIEW("userowcolumnprovider.qml");

    auto model = TestModelAsVariant(10, 10);

    tableView->setModel(model);
    QVERIFY(tableView->columnWidthProvider().isCallable());

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems) {
        // expectedWidth mirrors the expected return value of the assigned javascript function
        qreal expectedWidth = fxItem->cell.x() + 10;
        QCOMPARE(fxItem->item->width(), expectedWidth);
    }
}

void tst_QQuickTableView::checkColumnWidthProviderInvalidReturnValues()
{
    // Check that we fall back to use default columns widths, if you
    // assign a function to columnWidthProvider that returns invalid values.
    LOAD_TABLEVIEW("usefaultyrowcolumnprovider.qml");

    auto model = TestModelAsVariant(10, 10);

    tableView->setModel(model);

    QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*implicitHeight.*zero"));

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems)
        QCOMPARE(fxItem->item->width(), kDefaultColumnWidth);
}

void tst_QQuickTableView::checkColumnWidthProviderNegativeReturnValue()
{
    // Check that we fall back to use the implicit width of the delegate
    // items if the columnWidthProvider return a negative number.
    LOAD_TABLEVIEW("userowcolumnprovider.qml");

    auto model = TestModelAsVariant(10, 10);
    view->rootObject()->setProperty("returnNegativeColumnWidth", true);

    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems)
        QCOMPARE(fxItem->item->width(), 20);
}

void tst_QQuickTableView::checkColumnWidthProviderNotCallable()
{
    // Check that we fall back to use default columns widths, if you
    // assign something to columnWidthProvider that is not callable.
    LOAD_TABLEVIEW("usefaultyrowcolumnprovider.qml");

    auto model = TestModelAsVariant(10, 10);

    tableView->setModel(model);
    tableView->setRowHeightProvider(QJSValue());
    tableView->setColumnWidthProvider(QJSValue(10));

    QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".Provider.*function"));

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems)
        QCOMPARE(fxItem->item->width(), kDefaultColumnWidth);
}

void tst_QQuickTableView::checkRowHeightWithoutProvider()
{
    // Checks that a function isn't assigned to the rowHeightProvider property
    // and that the row height is then equal to sizeHintForRow.
    LOAD_TABLEVIEW("alternatingrowheightcolumnwidth.qml");

    auto model = TestModelAsVariant(10, 10);
    QVERIFY(tableView->rowHeightProvider().isUndefined());

    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    for (const int row : tableViewPrivate->loadedRows.keys()) {
        const qreal expectedRowHeight = tableViewPrivate->sizeHintForRow(row);
        for (const int column : tableViewPrivate->loadedColumns.keys()) {
            const auto item = tableViewPrivate->loadedTableItem(QPoint(column, row))->item;
            QCOMPARE(item->height(), expectedRowHeight);
        }
    }
}

void tst_QQuickTableView::checkRowHeightProvider()
{
    // Check that you can assign a function to the columnWidthProvider property, and
    // that it's used to control (and override) the width of the columns.
    LOAD_TABLEVIEW("userowcolumnprovider.qml");

    auto model = TestModelAsVariant(10, 10);

    tableView->setModel(model);
    QVERIFY(tableView->rowHeightProvider().isCallable());

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems) {
        // expectedWidth mirrors the expected return value of the assigned javascript function
        qreal expectedHeight = fxItem->cell.y() + 10;
        QCOMPARE(fxItem->item->height(), expectedHeight);
    }
}

void tst_QQuickTableView::checkRowHeightProviderInvalidReturnValues()
{
    // Check that we fall back to use default row heights, if you
    // assign a function to rowHeightProvider that returns invalid values.
    LOAD_TABLEVIEW("usefaultyrowcolumnprovider.qml");

    auto model = TestModelAsVariant(10, 10);

    tableView->setModel(model);

    QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*implicitHeight.*zero"));

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems)
        QCOMPARE(fxItem->item->height(), kDefaultRowHeight);
}

void tst_QQuickTableView::checkRowHeightProviderNegativeReturnValue()
{
    // Check that we fall back to use the implicit height of the delegate
    // items if the rowHeightProvider return a negative number.
    LOAD_TABLEVIEW("userowcolumnprovider.qml");

    auto model = TestModelAsVariant(10, 10);
    view->rootObject()->setProperty("returnNegativeRowHeight", true);

    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems)
        QCOMPARE(fxItem->item->height(), 20);
}

void tst_QQuickTableView::checkRowHeightProviderNotCallable()
{
    // Check that we fall back to use default row heights, if you
    // assign something to rowHeightProvider that is not callable.
    LOAD_TABLEVIEW("usefaultyrowcolumnprovider.qml");

    auto model = TestModelAsVariant(10, 10);

    tableView->setModel(model);

    tableView->setColumnWidthProvider(QJSValue());
    tableView->setRowHeightProvider(QJSValue(10));

    QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*Provider.*function"));

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems)
        QCOMPARE(fxItem->item->height(), kDefaultRowHeight);
}

void tst_QQuickTableView::checkForceLayoutFunction()
{
    // When we set the 'columnWidths' property in the test file, the
    // columnWidthProvider should return other values than it did during
    // start-up. Check that this takes effect after a call to the 'forceLayout()' function.
    LOAD_TABLEVIEW("forcelayout.qml");

    const char *propertyName = "columnWidths";
    auto model = TestModelAsVariant(10, 10);

    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    // Check that the initial column widths are as specified in the QML file
    const qreal initialColumnWidth = view->rootObject()->property(propertyName).toReal();
    for (auto fxItem : tableViewPrivate->loadedItems)
        QCOMPARE(fxItem->item->width(), initialColumnWidth);

    // Change the return value from the columnWidthProvider to something else
    const qreal newColumnWidth = 100;
    view->rootObject()->setProperty(propertyName, newColumnWidth);
    tableView->forceLayout();
    // We don't have to polish; The re-layout happens immediately

    for (auto fxItem : tableViewPrivate->loadedItems)
        QCOMPARE(fxItem->item->width(), newColumnWidth);
}

void tst_QQuickTableView::checkContentWidthAndHeight()
{
    // Check that contentWidth/Height reports the correct size of the
    // table, based on knowledge of the rows and columns that has been loaded.
    LOAD_TABLEVIEW("contentwidthheight.qml");

    // Vertical and horizontal properties should be mirrored, so we only have
    // to do the calculations once, and use them for both axis, below.
    QCOMPARE(tableView->width(), tableView->height());
    QCOMPARE(tableView->rowSpacing(), tableView->columnSpacing());

    const int tableSize = 100;
    const int cellSizeSmall = 100;
    const int spacing = 1;
    auto model = TestModelAsVariant(tableSize, tableSize);

    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    const qreal expectedSizeInit = (tableSize * cellSizeSmall) + ((tableSize - 1) * spacing);
    QCOMPARE(tableView->contentWidth(), expectedSizeInit);
    QCOMPARE(tableView->contentHeight(), expectedSizeInit);
    QCOMPARE(tableViewPrivate->averageEdgeSize.width(), cellSizeSmall);
    QCOMPARE(tableViewPrivate->averageEdgeSize.height(), cellSizeSmall);

    // Flick to the end, and check that content width/height stays unchanged
    tableView->setContentX(tableView->contentWidth() - tableView->width());
    tableView->setContentY(tableView->contentHeight() - tableView->height());

    QCOMPARE(tableView->contentWidth(), expectedSizeInit);
    QCOMPARE(tableView->contentHeight(), expectedSizeInit);

    // Flick back to start
    tableView->setContentX(0);
    tableView->setContentY(0);

    // Since we move the viewport more than a page, tableview
    // will jump to the new position and do a rebuild.
    QVERIFY(tableViewPrivate->polishScheduled);
    QVERIFY(tableViewPrivate->scheduledRebuildOptions);
    WAIT_UNTIL_POLISHED;

    // We should still have the same content width/height as when we started
    QCOMPARE(tableView->contentWidth(), expectedSizeInit);
    QCOMPARE(tableView->contentHeight(), expectedSizeInit);
}

void tst_QQuickTableView::checkPageFlicking()
{
    // Check that we rebuild the table instead of refilling edges, if the viewport moves
    // more than a page (the size of TableView).
    LOAD_TABLEVIEW("plaintableview.qml");

    const int cellWidth = 100;
    const int cellHeight = 50;
    auto model = TestModelAsVariant(10000, 10000);
    const auto &loadedRows = tableViewPrivate->loadedRows;
    const auto &loadedColumns = tableViewPrivate->loadedColumns;

    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    // Sanity check startup table
    QCOMPARE(tableViewPrivate->topRow(), 0);
    QCOMPARE(tableViewPrivate->leftColumn(), 0);
    QCOMPARE(loadedRows.count(), tableView->height() / cellHeight);
    QCOMPARE(loadedColumns.count(), tableView->width() / cellWidth);

    // Since all cells have the same size, the average row/column
    // size found by TableView should be exactly equal to this.
    QCOMPARE(tableViewPrivate->averageEdgeSize.width(), cellWidth);
    QCOMPARE(tableViewPrivate->averageEdgeSize.height(), cellHeight);

    QCOMPARE(tableViewPrivate->scheduledRebuildOptions, QQuickTableViewPrivate::RebuildOption::None);

    // Flick 5000 columns to the right, and check that this triggers a
    // rebuild, and that we end up at the expected top-left.
    const int flickToColumn = 5000;
    const qreal columnSpacing = tableView->columnSpacing();
    const qreal flickToColumnInPixels = ((cellWidth + columnSpacing) * flickToColumn) - columnSpacing;
    tableView->setContentX(flickToColumnInPixels);

    QVERIFY(tableViewPrivate->scheduledRebuildOptions & QQuickTableViewPrivate::RebuildOption::ViewportOnly);
    QVERIFY(tableViewPrivate->scheduledRebuildOptions & QQuickTableViewPrivate::RebuildOption::CalculateNewTopLeftColumn);
    QVERIFY(!(tableViewPrivate->scheduledRebuildOptions & QQuickTableViewPrivate::RebuildOption::CalculateNewTopLeftRow));

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->topRow(), 0);
    QCOMPARE(tableViewPrivate->leftColumn(), flickToColumn);
    QCOMPARE(loadedColumns.count(), tableView->width() / cellWidth);
    QCOMPARE(loadedRows.count(), tableView->height() / cellHeight);

    // Flick 5000 rows down as well. Since flicking down should only calculate a new row (but
    // keep the current column), we deliberatly change the average width to check that it's
    // actually ignored by the rebuild, and that the column stays the same.
    tableViewPrivate->averageEdgeSize.rwidth() /= 2;

    const int flickToRow = 5000;
    const qreal rowSpacing = tableView->rowSpacing();
    const qreal flickToRowInPixels = ((cellHeight + rowSpacing) * flickToRow) - rowSpacing;
    tableView->setContentY(flickToRowInPixels);

    QVERIFY(tableViewPrivate->scheduledRebuildOptions & QQuickTableViewPrivate::RebuildOption::ViewportOnly);
    QVERIFY(!(tableViewPrivate->scheduledRebuildOptions & QQuickTableViewPrivate::RebuildOption::CalculateNewTopLeftColumn));
    QVERIFY(tableViewPrivate->scheduledRebuildOptions & QQuickTableViewPrivate::RebuildOption::CalculateNewTopLeftRow);

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->topRow(), flickToColumn);
    QCOMPARE(tableViewPrivate->leftColumn(), flickToRow);
    QCOMPARE(loadedRows.count(), tableView->height() / cellHeight);
    QCOMPARE(loadedColumns.count(), tableView->width() / cellWidth);
}

void tst_QQuickTableView::checkExplicitContentWidthAndHeight()
{
    // Check that you can set a custom contentWidth/Height, and that
    // TableView doesn't override it while loading more rows and columns.
    LOAD_TABLEVIEW("contentwidthheight.qml");

    tableView->setContentWidth(1000);
    tableView->setContentHeight(1000);
    QCOMPARE(tableView->contentWidth(), 1000);
    QCOMPARE(tableView->contentHeight(), 1000);

    auto model = TestModelAsVariant(100, 100);
    tableView->setModel(model);
    WAIT_UNTIL_POLISHED;

    // Flick somewhere. It should not affect the contentWidth/Height
    tableView->setContentX(500);
    tableView->setContentY(500);
    QCOMPARE(tableView->contentWidth(), 1000);
    QCOMPARE(tableView->contentHeight(), 1000);
}

void tst_QQuickTableView::checkExtents_origin()
{
    // Check that if the beginning of the content view doesn't match the
    // actual size of the table, origin will be adjusted to make it fit.
    LOAD_TABLEVIEW("contentwidthheight.qml");

    const int rows = 10;
    const int columns = rows;
    const qreal columnWidth = 100;
    const qreal rowHeight = 100;
    const qreal actualTableSize = columns * columnWidth;

    // Set a content size that is far too large
    // compared to the size of the table.
    tableView->setContentWidth(actualTableSize * 2);
    tableView->setContentHeight(actualTableSize * 2);
    tableView->setRowSpacing(0);
    tableView->setColumnSpacing(0);
    tableView->setLeftMargin(0);
    tableView->setRightMargin(0);
    tableView->setTopMargin(0);
    tableView->setBottomMargin(0);

    auto model = TestModelAsVariant(rows, columns);
    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    // Flick slowly to column 5 (to avoid rebuilds). Flick two columns at a
    // time to ensure that we create a gap before TableView gets a chance to
    // adjust endExtent first. This gap on the right side will make TableView
    // move the table to move to the edge. Because of this, the table will not
    // be aligned at the start of the content view when we next flick back again.
    // And this will cause origin to move.
    for (int x = 0; x <= 6; x += 2) {
        tableView->setContentX(x * columnWidth);
        tableView->setContentY(x * rowHeight);
    }

    // Check that the table has now been moved one column to the right
    // (One column because that's how far outside the table we ended up flicking above).
    QCOMPARE(tableViewPrivate->loadedTableOuterRect.right(), actualTableSize + columnWidth);

    // Flick back one column at a time so that TableView detects that the first
    // column is not at the origin before the "table move" logic kicks in. This
    // will make TableView adjust the origin.
    for (int x = 6; x >= 0; x -= 1) {
        tableView->setContentX(x * columnWidth);
        tableView->setContentY(x * rowHeight);
    }

    // The origin will be moved with the same offset that the table was
    // moved on the right side earlier, which is one column length.
    QCOMPARE(tableViewPrivate->origin.x(), columnWidth);
    QCOMPARE(tableViewPrivate->origin.y(), rowHeight);
}

void tst_QQuickTableView::checkExtents_endExtent()
{
    // Check that if we the content view size doesn't match the actual size
    // of the table, endExtent will be adjusted to make it fit (so that
    // e.g the the flicking will bounce to a stop at the edge of the table).
    LOAD_TABLEVIEW("contentwidthheight.qml");

    const int rows = 10;
    const int columns = rows;
    const qreal columnWidth = 100;
    const qreal rowHeight = 100;
    const qreal actualTableSize = columns * columnWidth;

    // Set a content size that is far too large
    // compared to the size of the table.
    tableView->setContentWidth(actualTableSize * 2);
    tableView->setContentHeight(actualTableSize * 2);
    tableView->setRowSpacing(0);
    tableView->setColumnSpacing(0);
    tableView->setLeftMargin(0);
    tableView->setRightMargin(0);
    tableView->setTopMargin(0);
    tableView->setBottomMargin(0);

    auto model = TestModelAsVariant(rows, columns);
    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    // Flick slowly to column 5 (to avoid rebuilds). This will flick the table to
    // the last column in the model. But since there still is a lot space left in
    // the content view, endExtent will be set accordingly to compensate.
    for (int x = 1; x <= 5; x++)
        tableView->setContentX(x * columnWidth);
    QCOMPARE(tableViewPrivate->rightColumn(), columns - 1);
    qreal expectedEndExtentWidth = actualTableSize - tableView->contentWidth();
    QCOMPARE(tableViewPrivate->endExtent.width(), expectedEndExtentWidth);

    for (int y = 1; y <= 5; y++)
        tableView->setContentY(y * rowHeight);
    QCOMPARE(tableViewPrivate->bottomRow(), rows - 1);
    qreal expectedEndExtentHeight = actualTableSize - tableView->contentHeight();
    QCOMPARE(tableViewPrivate->endExtent.height(), expectedEndExtentHeight);
}

void tst_QQuickTableView::checkExtents_moveTableToEdge()
{
    // Check that if we the content view size doesn't match the actual
    // size of the table, and we fast-flick the viewport to outside
    // the table, we end up moving the table back into the viewport to
    // avoid any visual glitches.
    LOAD_TABLEVIEW("contentwidthheight.qml");

    const int rows = 10;
    const int columns = rows;
    const qreal columnWidth = 100;
    const qreal rowHeight = 100;
    const qreal actualTableSize = columns * columnWidth;

    // Set a content size that is far to large
    // compared to the size of the table.
    tableView->setContentWidth(actualTableSize * 2);
    tableView->setContentHeight(actualTableSize * 2);
    tableView->setRowSpacing(0);
    tableView->setColumnSpacing(0);
    tableView->setLeftMargin(0);
    tableView->setRightMargin(0);
    tableView->setTopMargin(0);
    tableView->setBottomMargin(0);

    auto model = TestModelAsVariant(rows, columns);
    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    // Flick slowly to column 5 (to avoid rebuilds). Flick two columns at a
    // time to ensure that we create a gap before TableView gets a chance to
    // adjust endExtent first. This gap on the right side will make TableView
    // move the table to the edge (in addition to adjusting the extents, but that
    // will happen in a subsequent polish, and is not for this test verify).
    for (int x = 0; x <= 6; x += 2)
        tableView->setContentX(x * columnWidth);
    QCOMPARE(tableViewPrivate->rightColumn(), columns - 1);
    QCOMPARE(tableViewPrivate->loadedTableOuterRect, tableViewPrivate->viewportRect);

    for (int y = 0; y <= 6; y += 2)
        tableView->setContentY(y * rowHeight);
    QCOMPARE(tableViewPrivate->bottomRow(), rows - 1);
    QCOMPARE(tableViewPrivate->loadedTableOuterRect, tableViewPrivate->viewportRect);

    for (int x = 6; x >= 0; x -= 2)
        tableView->setContentX(x * columnWidth);
    QCOMPARE(tableViewPrivate->leftColumn(), 0);
    QCOMPARE(tableViewPrivate->loadedTableOuterRect, tableViewPrivate->viewportRect);

    for (int y = 6; y >= 0; y -= 2)
        tableView->setContentY(y * rowHeight);
    QCOMPARE(tableViewPrivate->topRow(), 0);
    QCOMPARE(tableViewPrivate->loadedTableOuterRect, tableViewPrivate->viewportRect);
}

void tst_QQuickTableView::checkContentXY()
{
    // Check that you can bind contentX and contentY to
    // e.g show the center of the table at start-up
    LOAD_TABLEVIEW("setcontentpos.qml");

    auto model = TestModelAsVariant(10, 10);
    tableView->setModel(model);
    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableView->width(), 400);
    QCOMPARE(tableView->height(), 400);
    QCOMPARE(tableView->contentWidth(), 1000);
    QCOMPARE(tableView->contentHeight(), 1000);

    // Check that the content item is positioned according
    // to the binding in the QML file (which will set the
    // viewport to be at the center of the table).
    const qreal expectedXY = (tableView->contentWidth() - tableView->width()) / 2;
    QCOMPARE(tableView->contentX(), expectedXY);
    QCOMPARE(tableView->contentY(), expectedXY);

    // Check that we end up at the correct top-left cell:
    const qreal delegateWidth = tableViewPrivate->loadedItems.values().first()->item->width();
    const int expectedCellXY = qCeil(expectedXY / delegateWidth);
    QCOMPARE(tableViewPrivate->leftColumn(), expectedCellXY);
    QCOMPARE(tableViewPrivate->topRow(), expectedCellXY);
}

void tst_QQuickTableView::noDelegate()
{
    // Check that you can skip setting a delegate without
    // it causing any problems (like crashing or asserting).
    // And then set a delegate, and do a quick check that the
    // view gets populated as expected.
    LOAD_TABLEVIEW("plaintableview.qml");

    const int rows = 5;
    const int columns = 5;
    auto model = TestModelAsVariant(columns, rows);
    tableView->setModel(model);

    // Start with no delegate, and check
    // that we end up with no items in the table.
    tableView->setDelegate(nullptr);

    WAIT_UNTIL_POLISHED;

    auto items = tableViewPrivate->loadedItems;
    QVERIFY(items.isEmpty());

    // Set a delegate, and check that we end
    // up with the expected number of items.
    auto delegate = view->rootObject()->property("delegate").value<QQmlComponent *>();
    QVERIFY(delegate);
    tableView->setDelegate(delegate);

    WAIT_UNTIL_POLISHED;

    items = tableViewPrivate->loadedItems;
    QCOMPARE(items.count(), rows * columns);

    // And then unset the delegate again, and check
    // that we end up with no items.
    tableView->setDelegate(nullptr);

    WAIT_UNTIL_POLISHED;

    items = tableViewPrivate->loadedItems;
    QVERIFY(items.isEmpty());
}

void tst_QQuickTableView::changeDelegateDuringUpdate()
{
    // Check that you can change the delegate (set it to null)
    // while the TableView is busy loading the table.
    LOAD_TABLEVIEW("changemodelordelegateduringupdate.qml");

    auto model = TestModelAsVariant(1, 1);
    tableView->setModel(model);
    view->rootObject()->setProperty("changeDelegate", true);

    WAIT_UNTIL_POLISHED;

    // We should no longer have a delegate, and no
    // items should therefore be loaded.
    QCOMPARE(tableView->delegate(), nullptr);
    QCOMPARE(tableViewPrivate->loadedItems.size(), 0);

    // Even if the delegate is missing, we still report
    // the correct size of the model
    QCOMPARE(tableView->rows(), 1);
    QCOMPARE(tableView->columns(), 1);
};

void tst_QQuickTableView::changeModelDuringUpdate()
{
    // Check that you can change the model (set it to null)
    // while the TableView is buzy loading the table.
    LOAD_TABLEVIEW("changemodelordelegateduringupdate.qml");

    auto model = TestModelAsVariant(1, 1);
    tableView->setModel(model);
    view->rootObject()->setProperty("changeModel", true);

    WAIT_UNTIL_POLISHED;

    // We should no longer have a model, and the no
    // items should therefore be loaded.
    QVERIFY(tableView->model().isNull());
    QCOMPARE(tableViewPrivate->loadedItems.size(), 0);

    // The empty model has no rows or columns
    QCOMPARE(tableView->rows(), 0);
    QCOMPARE(tableView->columns(), 0);
};

void tst_QQuickTableView::countDelegateItems_data()
{
    QTest::addColumn<QVariant>("model");
    QTest::addColumn<int>("count");

    QTest::newRow("QAIM 1x1") << TestModelAsVariant(1, 1) << 1;
    QTest::newRow("QAIM 2x1") << TestModelAsVariant(2, 1) << 2;
    QTest::newRow("QAIM 1x2") << TestModelAsVariant(1, 2) << 2;
    QTest::newRow("QAIM 2x2") << TestModelAsVariant(2, 2) << 4;
    QTest::newRow("QAIM 4x4") << TestModelAsVariant(4, 4) << 16;

    QTest::newRow("Number model 1") << QVariant::fromValue(1) << 1;
    QTest::newRow("Number model 4") << QVariant::fromValue(4) << 4;

    QTest::newRow("QStringList 1") << QVariant::fromValue(QStringList() << "one") << 1;
    QTest::newRow("QStringList 4") << QVariant::fromValue(QStringList() << "one" << "two" << "three" << "four") << 4;
}

void tst_QQuickTableView::countDelegateItems()
{
    // Assign different models of various sizes, and check that the number of
    // delegate items in the view matches the size of the model. Note that for
    // this test to be valid, all items must be within the visible area of the view.
    QFETCH(QVariant, model);
    QFETCH(int, count);
    LOAD_TABLEVIEW("plaintableview.qml");

    tableView->setModel(model);
    WAIT_UNTIL_POLISHED;

    // Check that tableview internals contain the expected number of items
    auto const items = tableViewPrivate->loadedItems;
    QCOMPARE(items.count(), count);

    // Check that this also matches the items found in the view
    auto foundItems = findItems<QQuickItem>(tableView, kDelegateObjectName);
    QCOMPARE(foundItems.count(), count);
}

void tst_QQuickTableView::checkLayoutOfEqualSizedDelegateItems_data()
{
    QTest::addColumn<QVariant>("model");
    QTest::addColumn<QSize>("tableSize");
    QTest::addColumn<QSizeF>("spacing");
    QTest::addColumn<QMarginsF>("margins");

    // Check spacing together with different table setups
    QTest::newRow("QAIM 1x1 1,1") << TestModelAsVariant(1, 1) << QSize(1, 1) << QSizeF(1, 1) << QMarginsF(0, 0, 0, 0);
    QTest::newRow("QAIM 5x5 0,0") << TestModelAsVariant(5, 5) << QSize(5, 5) << QSizeF(0, 0) << QMarginsF(0, 0, 0, 0);
    QTest::newRow("QAIM 5x5 1,0") << TestModelAsVariant(5, 5) << QSize(5, 5) << QSizeF(1, 0) << QMarginsF(0, 0, 0, 0);
    QTest::newRow("QAIM 5x5 0,1") << TestModelAsVariant(5, 5) << QSize(5, 5) << QSizeF(0, 1) << QMarginsF(0, 0, 0, 0);

    // Check spacing together with margins
    QTest::newRow("QAIM 1x1 1,1 5555") << TestModelAsVariant(1, 1) << QSize(1, 1) << QSizeF(1, 1) << QMarginsF(5, 5, 5, 5);
    QTest::newRow("QAIM 4x4 0,0 3333") << TestModelAsVariant(4, 4) << QSize(4, 4) << QSizeF(0, 0) << QMarginsF(3, 3, 3, 3);
    QTest::newRow("QAIM 4x4 2,2 1234") << TestModelAsVariant(4, 4) << QSize(4, 4) << QSizeF(2, 2) << QMarginsF(1, 2, 3, 4);

    // Check "list" models
    QTest::newRow("NumberModel 1x4, 0000") << QVariant::fromValue(4) << QSize(1, 4) << QSizeF(1, 1) << QMarginsF(0, 0, 0, 0);
    QTest::newRow("QStringList 1x4, 0,0 1111") << QVariant::fromValue(QStringList() << "one" << "two" << "three" << "four")
                                               << QSize(1, 4) << QSizeF(0, 0) << QMarginsF(1, 1, 1, 1);
}

void tst_QQuickTableView::checkLayoutOfEqualSizedDelegateItems()
{
    // Check that the geometry of the delegate items are correct
    QFETCH(QVariant, model);
    QFETCH(QSize, tableSize);
    QFETCH(QSizeF, spacing);
    QFETCH(QMarginsF, margins);
    LOAD_TABLEVIEW("plaintableview.qml");

    const qreal expectedItemWidth = 100;
    const qreal expectedItemHeight = 50;
    const int expectedItemCount = tableSize.width() * tableSize.height();

    tableView->setModel(model);
    tableView->setRowSpacing(spacing.height());
    tableView->setColumnSpacing(spacing.width());

    // Setting margins on Flickable should not affect the layout of the
    // delegate items, since the margins is "transparent" to the TableView.
    tableView->setLeftMargin(margins.left());
    tableView->setTopMargin(margins.top());
    tableView->setRightMargin(margins.right());
    tableView->setBottomMargin(margins.bottom());

    WAIT_UNTIL_POLISHED;

    auto const items = tableViewPrivate->loadedItems;
    QVERIFY(!items.isEmpty());

    for (int i = 0; i < expectedItemCount; ++i) {
        const QQuickItem *item = items[i]->item;
        QVERIFY(item);
        QCOMPARE(item->parentItem(), tableView->contentItem());

        const QPoint cell = getContextRowAndColumn(item);
        qreal expectedX = cell.x() * (expectedItemWidth + spacing.width());
        qreal expectedY = cell.y() * (expectedItemHeight + spacing.height());
        QCOMPARE(item->x(), expectedX);
        QCOMPARE(item->y(), expectedY);
        QCOMPARE(item->z(), 1);
        QCOMPARE(item->width(), expectedItemWidth);
        QCOMPARE(item->height(), expectedItemHeight);
    }
}

void tst_QQuickTableView::checkFocusRemoved_data()
{
    QTest::addColumn<QString>("focusedItemProp");

    QTest::newRow("delegate root") << QStringLiteral("delegateRoot");
    QTest::newRow("delegate child") << QStringLiteral("delegateChild");
}

void tst_QQuickTableView::checkFocusRemoved()
{
    // Check that we clear the focus of a delegate item when
    // a child of the delegate item has focus, and the cell is
    // flicked out of view.
    QFETCH(QString, focusedItemProp);
    LOAD_TABLEVIEW("tableviewfocus.qml");

    auto model = TestModelAsVariant(100, 100);
    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    auto const item = tableViewPrivate->loadedTableItem(QPoint(0, 0))->item;
    auto const focusedItem = qvariant_cast<QQuickItem *>(item->property(focusedItemProp.toUtf8().data()));
    QVERIFY(focusedItem);
    QCOMPARE(tableView->hasActiveFocus(), false);
    QCOMPARE(focusedItem->hasActiveFocus(), false);

    focusedItem->forceActiveFocus();
    QCOMPARE(tableView->hasActiveFocus(), true);
    QCOMPARE(focusedItem->hasActiveFocus(), true);

    // Flick the focused cell out, and check that none of the
    // items in the table has focus (which means that the reused
    // item lost focus when it was flicked out). But the tableview
    // itself will maintain active focus.
    tableView->setContentX(500);
    QCOMPARE(tableView->hasActiveFocus(), true);
    for (auto fxItem : tableViewPrivate->loadedItems) {
        auto const focusedItem2 = qvariant_cast<QQuickItem *>(fxItem->item->property(focusedItemProp.toUtf8().data()));
        QCOMPARE(focusedItem2->hasActiveFocus(), false);
    }
}

void tst_QQuickTableView::fillTableViewButNothingMore_data()
{
    QTest::addColumn<QSizeF>("spacing");

    QTest::newRow("0 0,0 0") << QSizeF(0, 0);
    QTest::newRow("0 10,10 0") << QSizeF(10, 10);
    QTest::newRow("100 10,10 0") << QSizeF(10, 10);
    QTest::newRow("0 0,0 100") << QSizeF(0, 0);
    QTest::newRow("0 10,10 100") << QSizeF(10, 10);
    QTest::newRow("100 10,10 100") << QSizeF(10, 10);
}

void tst_QQuickTableView::fillTableViewButNothingMore()
{
    // Check that we end up filling the whole visible part of
    // the tableview with cells, but nothing more.
    QFETCH(QSizeF, spacing);
    LOAD_TABLEVIEW("plaintableview.qml");

    const int rows = 100;
    const int columns = 100;
    auto model = TestModelAsVariant(rows, columns);

    tableView->setModel(model);
    tableView->setRowSpacing(spacing.height());
    tableView->setColumnSpacing(spacing.width());

    WAIT_UNTIL_POLISHED;

    auto const topLeftFxItem = tableViewPrivate->loadedTableItem(QPoint(0, 0));
    auto const topLeftItem = topLeftFxItem->item;

    auto const bottomRightLoadedCell = QPoint(tableViewPrivate->rightColumn(), tableViewPrivate->bottomRow());
    auto const bottomRightFxItem = tableViewPrivate->loadedTableItem(bottomRightLoadedCell);
    auto const bottomRightItem = bottomRightFxItem->item;
    const QPoint bottomRightCell = getContextRowAndColumn(bottomRightItem.data());

    // Check that the right-most item is overlapping the right edge of the view
    QVERIFY(bottomRightItem->x() < tableView->width());
    QVERIFY(bottomRightItem->x() + bottomRightItem->width() >= tableView->width() - spacing.width());

    // Check that the actual number of columns matches what we expect
    qreal cellWidth = bottomRightItem->width() + spacing.width();
    int expectedColumns = qCeil(tableView->width() / cellWidth);
    int actualColumns = bottomRightCell.x() + 1;
    QCOMPARE(actualColumns, expectedColumns);

    // Check that the bottom-most item is overlapping the bottom edge of the view
    QVERIFY(bottomRightItem->y() < tableView->height());
    QVERIFY(bottomRightItem->y() + bottomRightItem->height() >= tableView->height() - spacing.height());

    // Check that the actual number of rows matches what we expect
    qreal cellHeight = bottomRightItem->height() + spacing.height();
    int expectedRows = qCeil(tableView->height() / cellHeight);
    int actualRows = bottomRightCell.y() + 1;
    QCOMPARE(actualRows, expectedRows);
}

void tst_QQuickTableView::checkInitialAttachedProperties_data()
{
    QTest::addColumn<QVariant>("model");

    QTest::newRow("QAIM") << TestModelAsVariant(4, 4);
    QTest::newRow("Number model") << QVariant::fromValue(4);
    QTest::newRow("QStringList") << QVariant::fromValue(QStringList() << "0" << "1" << "2" << "3");
}

void tst_QQuickTableView::checkInitialAttachedProperties()
{
    // Check that the context and attached properties inside
    // the delegate items are what we expect at start-up.
    QFETCH(QVariant, model);
    LOAD_TABLEVIEW("plaintableview.qml");

    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems) {
        const int index = fxItem->index;
        const auto item = fxItem->item;
        const auto context = qmlContext(item.data());
        const QPoint cell = tableViewPrivate->cellAtModelIndex(index);
        const int contextIndex = context->contextProperty("index").toInt();
        const QPoint contextCell = getContextRowAndColumn(item.data());
        const QString contextModelData = context->contextProperty("modelData").toString();

        QCOMPARE(contextCell.y(), cell.y());
        QCOMPARE(contextCell.x(), cell.x());
        QCOMPARE(contextIndex, index);
        QCOMPARE(contextModelData, QStringLiteral("%1").arg(cell.y()));
        QCOMPARE(getAttachedObject(item)->view(), tableView);
    }
}

void tst_QQuickTableView::checkSpacingValues()
{
    LOAD_TABLEVIEW("tableviewdefaultspacing.qml");

    int rowCount = 9;
    int columnCount = 9;
    int delegateWidth = 15;
    int delegateHeight = 10;
    auto model = TestModelAsVariant(rowCount, columnCount);
    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    // Default spacing : 0
    QCOMPARE(tableView->rowSpacing(), 0);
    QCOMPARE(tableView->columnSpacing(), 0);

    tableView->polish();
    WAIT_UNTIL_POLISHED;

    const qreal expectedInitialContentWidth = columnCount * (delegateWidth + tableView->columnSpacing()) - tableView->columnSpacing();
    const qreal expectedInitialContentHeight = rowCount * (delegateHeight + tableView->rowSpacing()) - tableView->rowSpacing();
    QCOMPARE(tableView->contentWidth(), expectedInitialContentWidth);
    QCOMPARE(tableView->contentHeight(), expectedInitialContentHeight);

    // Valid spacing assignment
    tableView->setRowSpacing(42);
    tableView->setColumnSpacing(12);
    QCOMPARE(tableView->rowSpacing(), 42);
    QCOMPARE(tableView->columnSpacing(), 12);

    tableView->polish();
    WAIT_UNTIL_POLISHED;

    // Even after changing spacing, TableView will keep the initial guesstimated content size. The
    // reason is that deciding the content size based on the currently visible row/columns/spacing
    // will almost always be at a little bit wrong at best. So instead of pretending that TableView
    // knows what the size of the full table is, it sticks with the first guesstimate.
    QCOMPARE(tableView->contentWidth(), expectedInitialContentWidth);
    QCOMPARE(tableView->contentHeight(), expectedInitialContentHeight);

    // Invalid assignments (should ignore)
    tableView->setRowSpacing(-1);
    tableView->setColumnSpacing(-5);
    tableView->setRowSpacing(INFINITY);
    tableView->setColumnSpacing(INFINITY);
    tableView->setRowSpacing(NAN);
    tableView->setColumnSpacing(NAN);
    QCOMPARE(tableView->rowSpacing(), 42);
    QCOMPARE(tableView->columnSpacing(), 12);
}

void tst_QQuickTableView::checkDelegateParent()
{
    // Check that TableView sets the delegate parent before
    // bindings are evaluated, so that the app can bind to it.
    LOAD_TABLEVIEW("plaintableview.qml");

    auto model = TestModelAsVariant(100, 100);
    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    QVERIFY(view->rootObject()->property("delegateParentSetBeforeCompleted").toBool());
}

void tst_QQuickTableView::flick_data()
{
    QTest::addColumn<QSizeF>("spacing");
    QTest::addColumn<QMarginsF>("margins");
    QTest::addColumn<bool>("reuseItems");

    QTest::newRow("s:0 m:0 reuse") << QSizeF(0, 0) << QMarginsF(0, 0, 0, 0) << true;
    QTest::newRow("s:5 m:0 reuse") << QSizeF(5, 5) << QMarginsF(0, 0, 0, 0) << true;
    QTest::newRow("s:0 m:20 reuse") << QSizeF(0, 0) << QMarginsF(20, 20, 20, 20) << true;
    QTest::newRow("s:5 m:20 reuse") << QSizeF(5, 5) << QMarginsF(20, 20, 20, 20) << true;
    QTest::newRow("s:0 m:0") << QSizeF(0, 0) << QMarginsF(0, 0, 0, 0) << false;
    QTest::newRow("s:5 m:0") << QSizeF(5, 5) << QMarginsF(0, 0, 0, 0) << false;
    QTest::newRow("s:0 m:20") << QSizeF(0, 0) << QMarginsF(20, 20, 20, 20) << false;
    QTest::newRow("s:5 m:20") << QSizeF(5, 5) << QMarginsF(20, 20, 20, 20) << false;
}

void tst_QQuickTableView::flick()
{
    // Check that if we end up with the correct start and end column/row as we flick around
    // with different table configurations.
    QFETCH(QSizeF, spacing);
    QFETCH(QMarginsF, margins);
    QFETCH(bool, reuseItems);
    LOAD_TABLEVIEW("plaintableview.qml");

    const qreal delegateWidth = 100;
    const qreal delegateHeight = 50;
    const int visualColumnCount = 4;
    const int visualRowCount = 4;
    const qreal cellWidth = delegateWidth + spacing.width();
    const qreal cellHeight = delegateHeight + spacing.height();
    auto model = TestModelAsVariant(100, 100);

    tableView->setModel(model);
    tableView->setRowSpacing(spacing.height());
    tableView->setColumnSpacing(spacing.width());
    tableView->setLeftMargin(margins.left());
    tableView->setTopMargin(margins.top());
    tableView->setRightMargin(margins.right());
    tableView->setBottomMargin(margins.bottom());
    tableView->setReuseItems(reuseItems);
    tableView->setWidth(margins.left() + (visualColumnCount * cellWidth) - spacing.width());
    tableView->setHeight(margins.top() + (visualRowCount * cellHeight) - spacing.height());

    WAIT_UNTIL_POLISHED;

    // Check the "simple" case if the cells never lands egde-to-edge with the viewport. For
    // that case we only accept that visible row/columns are loaded.
    qreal flickValues[] = {0.5, 1.5, 4.5, 20.5, 10.5, 3.5, 1.5, 0.5};

    for (qreal cellsToFlick : flickValues) {
        // Flick to the beginning of the cell
        tableView->setContentX(cellsToFlick * cellWidth);
        tableView->setContentY(cellsToFlick * cellHeight);
        tableView->polish();

        WAIT_UNTIL_POLISHED;

        const int expectedTableLeft = int(cellsToFlick - int((margins.left() + spacing.width()) / cellWidth));
        const int expectedTableTop = int(cellsToFlick - int((margins.top() + spacing.height()) / cellHeight));

        QCOMPARE(tableViewPrivate->leftColumn(), expectedTableLeft);
        QCOMPARE(tableViewPrivate->rightColumn(), expectedTableLeft + visualColumnCount);
        QCOMPARE(tableViewPrivate->topRow(), expectedTableTop);
        QCOMPARE(tableViewPrivate->bottomRow(), expectedTableTop + visualRowCount);
    }
}

void tst_QQuickTableView::flickOvershoot_data()
{
    QTest::addColumn<QSizeF>("spacing");
    QTest::addColumn<QMarginsF>("margins");
    QTest::addColumn<bool>("reuseItems");

    QTest::newRow("s:0 m:0 reuse") << QSizeF(0, 0) << QMarginsF(0, 0, 0, 0) << true;
    QTest::newRow("s:5 m:0 reuse") << QSizeF(5, 5) << QMarginsF(0, 0, 0, 0) << true;
    QTest::newRow("s:0 m:20 reuse") << QSizeF(0, 0) << QMarginsF(20, 20, 20, 20) << true;
    QTest::newRow("s:5 m:20 reuse") << QSizeF(5, 5) << QMarginsF(20, 20, 20, 20) << true;
    QTest::newRow("s:0 m:0") << QSizeF(0, 0) << QMarginsF(0, 0, 0, 0) << false;
    QTest::newRow("s:5 m:0") << QSizeF(5, 5) << QMarginsF(0, 0, 0, 0) << false;
    QTest::newRow("s:0 m:20") << QSizeF(0, 0) << QMarginsF(20, 20, 20, 20) << false;
    QTest::newRow("s:5 m:20") << QSizeF(5, 5) << QMarginsF(20, 20, 20, 20) << false;
}

void tst_QQuickTableView::flickOvershoot()
{
    // Flick the table completely out and then in again, and see
    // that we still contains the expected rows/columns
    // Note that TableView always keeps top-left item loaded, even
    // when everything is flicked out of view.
    QFETCH(QSizeF, spacing);
    QFETCH(QMarginsF, margins);
    QFETCH(bool, reuseItems);
    LOAD_TABLEVIEW("plaintableview.qml");

    const int rowCount = 5;
    const int columnCount = 5;
    const qreal delegateWidth = 100;
    const qreal delegateHeight = 50;
    const qreal cellWidth = delegateWidth + spacing.width();
    const qreal cellHeight = delegateHeight + spacing.height();
    const qreal tableWidth = margins.left() + margins.right() + (cellWidth * columnCount) - spacing.width();
    const qreal tableHeight = margins.top() + margins.bottom() + (cellHeight * rowCount) - spacing.height();
    const int outsideMargin = 10;
    auto model = TestModelAsVariant(rowCount, columnCount);

    tableView->setModel(model);
    tableView->setRowSpacing(spacing.height());
    tableView->setColumnSpacing(spacing.width());
    tableView->setLeftMargin(margins.left());
    tableView->setTopMargin(margins.top());
    tableView->setRightMargin(margins.right());
    tableView->setBottomMargin(margins.bottom());
    tableView->setReuseItems(reuseItems);
    tableView->setWidth(tableWidth - margins.right() - cellWidth / 2);
    tableView->setHeight(tableHeight - margins.bottom() - cellHeight / 2);

    WAIT_UNTIL_POLISHED;

    // Flick table out of view left
    tableView->setContentX(-tableView->width() - outsideMargin);
    tableView->setContentY(0);
    tableView->polish();

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->leftColumn(), 0);
    QCOMPARE(tableViewPrivate->rightColumn(), 0);
    QCOMPARE(tableViewPrivate->topRow(), 0);
    QCOMPARE(tableViewPrivate->bottomRow(), rowCount - 1);

    // Flick table out of view right
    tableView->setContentX(tableWidth + outsideMargin);
    tableView->setContentY(0);
    tableView->polish();

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->leftColumn(), columnCount - 1);
    QCOMPARE(tableViewPrivate->rightColumn(), columnCount - 1);
    QCOMPARE(tableViewPrivate->topRow(), 0);
    QCOMPARE(tableViewPrivate->bottomRow(), rowCount - 1);

    // Flick table out of view on top
    tableView->setContentX(0);
    tableView->setContentY(-tableView->height() - outsideMargin);
    tableView->polish();

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->leftColumn(), 0);
    QCOMPARE(tableViewPrivate->rightColumn(), columnCount - 1);
    QCOMPARE(tableViewPrivate->topRow(), 0);
    QCOMPARE(tableViewPrivate->bottomRow(), 0);

    // Flick table out of view at the bottom
    tableView->setContentX(0);
    tableView->setContentY(tableHeight + outsideMargin);
    tableView->polish();

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->leftColumn(), 0);
    QCOMPARE(tableViewPrivate->rightColumn(), columnCount - 1);
    QCOMPARE(tableViewPrivate->topRow(), rowCount - 1);
    QCOMPARE(tableViewPrivate->bottomRow(), rowCount - 1);

    // Flick table out of view left and top at the same time
    tableView->setContentX(-tableView->width() - outsideMargin);
    tableView->setContentY(-tableView->height() - outsideMargin);
    tableView->polish();

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->leftColumn(), 0);
    QCOMPARE(tableViewPrivate->rightColumn(), 0);
    QCOMPARE(tableViewPrivate->topRow(), 0);
    QCOMPARE(tableViewPrivate->bottomRow(), 0);

    // Flick table back to origo
    tableView->setContentX(0);
    tableView->setContentY(0);
    tableView->polish();

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->leftColumn(), 0);
    QCOMPARE(tableViewPrivate->rightColumn(), columnCount - 1);
    QCOMPARE(tableViewPrivate->topRow(), 0);
    QCOMPARE(tableViewPrivate->bottomRow(), rowCount - 1);

    // Flick table out of view right and bottom at the same time
    tableView->setContentX(tableWidth + outsideMargin);
    tableView->setContentY(tableHeight + outsideMargin);
    tableView->polish();

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->leftColumn(), columnCount - 1);
    QCOMPARE(tableViewPrivate->rightColumn(), columnCount - 1);
    QCOMPARE(tableViewPrivate->topRow(), rowCount - 1);
    QCOMPARE(tableViewPrivate->bottomRow(), rowCount - 1);

    // Flick table back to origo
    tableView->setContentX(0);
    tableView->setContentY(0);
    tableView->polish();

    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableViewPrivate->leftColumn(), 0);
    QCOMPARE(tableViewPrivate->rightColumn(), columnCount - 1);
    QCOMPARE(tableViewPrivate->topRow(), 0);
    QCOMPARE(tableViewPrivate->bottomRow(), rowCount - 1);
}

void tst_QQuickTableView::checkRowColumnCount()
{
    // If we flick several columns (rows) at the same time, check that we don't
    // end up with loading more delegate items into memory than necessary. We
    // should free up columns as we go before loading new ones.
    LOAD_TABLEVIEW("countingtableview.qml");

    const char *maxDelegateCountProp = "maxDelegateCount";
    const qreal delegateWidth = 100;
    const qreal delegateHeight = 50;
    auto model = TestModelAsVariant(100, 100);
    const auto &loadedRows = tableViewPrivate->loadedRows;
    const auto &loadedColumns = tableViewPrivate->loadedColumns;

    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    // We expect that the number of created items after start-up should match
    //the size of the visible table, pluss one extra preloaded row and column.
    const int qmlCountAfterInit = view->rootObject()->property(maxDelegateCountProp).toInt();
    const int expectedCount = (loadedColumns.count() + 1) * (loadedRows.count() + 1);
    QCOMPARE(qmlCountAfterInit, expectedCount);

    // This test will keep track of the maximum number of delegate items TableView
    // had to show at any point while flicking (in countingtableview.qml). Because
    // of the geometries chosen for TableView and the delegate, only complete columns
    // will be shown at start-up.
    QVERIFY(loadedRows.count() > loadedColumns.count());
    QCOMPARE(tableViewPrivate->loadedTableOuterRect.width(), tableView->width());
    QCOMPARE(tableViewPrivate->loadedTableOuterRect.height(), tableView->height());

    // Flick half an item to the left+up, to force one extra column and row to load before we
    // start. By doing so, we end up showing the maximum number of rows and columns that will
    // ever be shown in the view. This will make things less complicated below, when checking
    // how many items that end up visible while flicking.
    tableView->setContentX(delegateWidth / 2);
    tableView->setContentY(delegateHeight / 2);
    const int qmlCountAfterFirstFlick = view->rootObject()->property(maxDelegateCountProp).toInt();

    // Flick a long distance right
    tableView->setContentX(tableView->width() * 2);

    const int qmlCountAfterLongFlick = view->rootObject()->property(maxDelegateCountProp).toInt();
    QCOMPARE(qmlCountAfterLongFlick, qmlCountAfterFirstFlick);

    // Flick a long distance down
    tableView->setContentX(tableView->height() * 2);

    const int qmlCountAfterDownFlick = view->rootObject()->property(maxDelegateCountProp).toInt();
    QCOMPARE(qmlCountAfterDownFlick, qmlCountAfterFirstFlick);

    // Flick a long distance left
    tableView->setContentX(0);

    const int qmlCountAfterLeftFlick = view->rootObject()->property(maxDelegateCountProp).toInt();
    QCOMPARE(qmlCountAfterLeftFlick, qmlCountAfterFirstFlick);

    // Flick a long distance up
    tableView->setContentY(0);

    const int qmlCountAfterUpFlick = view->rootObject()->property(maxDelegateCountProp).toInt();
    QCOMPARE(qmlCountAfterUpFlick, qmlCountAfterFirstFlick);
}

void tst_QQuickTableView::modelSignals()
{
    LOAD_TABLEVIEW("plaintableview.qml");

    TestModel model(1, 1);
    tableView->setModel(QVariant::fromValue(&model));
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 1);
    QCOMPARE(tableView->columns(), 1);

    QVERIFY(model.insertRows(0, 1));
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 2);
    QCOMPARE(tableView->columns(), 1);

    QVERIFY(model.removeRows(1, 1));
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 1);
    QCOMPARE(tableView->columns(), 1);

    model.insertColumns(1, 1);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 1);
    QCOMPARE(tableView->columns(), 2);

    model.removeColumns(1, 1);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 1);
    QCOMPARE(tableView->columns(), 1);

    model.setRowCount(10);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 10);
    QCOMPARE(tableView->columns(), 1);

    model.setColumnCount(10);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 10);
    QCOMPARE(tableView->columns(), 10);

    model.setRowCount(0);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 0);
    QCOMPARE(tableView->columns(), 10);

    model.setColumnCount(1);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 0);
    QCOMPARE(tableView->columns(), 1);

    model.setRowCount(10);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 10);
    QCOMPARE(tableView->columns(), 1);

    model.setColumnCount(10);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 10);
    QCOMPARE(tableView->columns(), 10);

    model.clear();
    model.setColumnCount(1);
    WAIT_UNTIL_POLISHED;
    QCOMPARE(tableView->rows(), 0);
    QCOMPARE(tableView->columns(), 1);
}

void tst_QQuickTableView::checkModelSignalsUpdateLayout()
{
    // Check that if the model rearranges rows and emit the
    // 'layoutChanged' signal, TableView will be updated correctly.
    LOAD_TABLEVIEW("plaintableview.qml");

    TestModel model(0, 1);
    tableView->setModel(QVariant::fromValue(&model));
    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableView->rows(), 0);
    QCOMPARE(tableView->columns(), 1);

    QString modelRow1Text = QStringLiteral("firstRow");
    QString modelRow2Text = QStringLiteral("secondRow");
    model.insertRow(0);
    model.insertRow(0);
    model.setModelData(QPoint(0, 0), QSize(1, 1), modelRow1Text);
    model.setModelData(QPoint(0, 1), QSize(1, 1), modelRow2Text);
    WAIT_UNTIL_POLISHED;

    QCOMPARE(tableView->rows(), 2);
    QCOMPARE(tableView->columns(), 1);

    QString delegate1text = tableViewPrivate->loadedTableItem(QPoint(0, 0))->item->property("modelDataBinding").toString();
    QString delegate2text = tableViewPrivate->loadedTableItem(QPoint(0, 1))->item->property("modelDataBinding").toString();
    QCOMPARE(delegate1text, modelRow1Text);
    QCOMPARE(delegate2text, modelRow2Text);

    model.swapRows(0, 1);
    WAIT_UNTIL_POLISHED;

    delegate1text = tableViewPrivate->loadedTableItem(QPoint(0, 0))->item->property("modelDataBinding").toString();
    delegate2text = tableViewPrivate->loadedTableItem(QPoint(0, 1))->item->property("modelDataBinding").toString();
    QCOMPARE(delegate1text, modelRow2Text);
    QCOMPARE(delegate2text, modelRow1Text);
}

void tst_QQuickTableView::dataChangedSignal()
{
    // Check that bindings to the model inside a delegate gets updated
    // when the model item they bind to changes.
    LOAD_TABLEVIEW("plaintableview.qml");

    const QString prefix(QStringLiteral("changed"));

    TestModel model(10, 10);
    tableView->setModel(QVariant::fromValue(&model));

    WAIT_UNTIL_POLISHED;

    for (auto fxItem : tableViewPrivate->loadedItems) {
        const auto item = tableViewPrivate->loadedTableItem(fxItem->cell)->item;
        const QString modelDataBindingProperty = item->property(kModelDataBindingProp).toString();
        QString expectedModelData = QString::number(fxItem->cell.y());
        QCOMPARE(modelDataBindingProperty, expectedModelData);
    }

    // Change one cell in the model
    model.setModelData(QPoint(0, 0), QSize(1, 1), prefix);

    for (auto fxItem : tableViewPrivate->loadedItems) {
        const QPoint cell = fxItem->cell;
        const auto modelIndex = model.index(cell.y(), cell.x());
        QString expectedModelData = model.data(modelIndex, Qt::DisplayRole).toString();

        const auto item = tableViewPrivate->loadedTableItem(fxItem->cell)->item;
        const QString modelDataBindingProperty = item->property(kModelDataBindingProp).toString();

        QCOMPARE(modelDataBindingProperty, expectedModelData);
    }

    // Change four cells in one go
    model.setModelData(QPoint(1, 0), QSize(2, 2), prefix);

    for (auto fxItem : tableViewPrivate->loadedItems) {
        const QPoint cell = fxItem->cell;
        const auto modelIndex = model.index(cell.y(), cell.x());
        QString expectedModelData = model.data(modelIndex, Qt::DisplayRole).toString();

        const auto item = tableViewPrivate->loadedTableItem(fxItem->cell)->item;
        const QString modelDataBindingProperty = item->property(kModelDataBindingProp).toString();

        QCOMPARE(modelDataBindingProperty, expectedModelData);
    }
}

void tst_QQuickTableView::checkThatPoolIsDrainedWhenReuseIsFalse()
{
    // Check that the reuse pool is drained
    // immediately when setting reuseItems to false.
    LOAD_TABLEVIEW("countingtableview.qml");

    auto model = TestModelAsVariant(100, 100);
    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    // The pool should now contain preloaded items
    QVERIFY(tableViewPrivate->tableModel->poolSize() > 0);
    tableView->setReuseItems(false);
    // The pool should now be empty
    QCOMPARE(tableViewPrivate->tableModel->poolSize(), 0);
}

void tst_QQuickTableView::checkIfDelegatesAreReused_data()
{
    QTest::addColumn<bool>("reuseItems");

    QTest::newRow("reuse = true") << true;
    QTest::newRow("reuse = false") << false;
}

void tst_QQuickTableView::checkIfDelegatesAreReused()
{
    // Check that we end up reusing delegate items while flicking if
    // TableView has reuseItems set to true, but otherwise not.
    QFETCH(bool, reuseItems);
    LOAD_TABLEVIEW("countingtableview.qml");

    const qreal delegateWidth = 100;
    const qreal delegateHeight = 50;
    const int pageFlickCount = 4;

    auto model = TestModelAsVariant(100, 100);
    tableView->setModel(model);
    tableView->setReuseItems(reuseItems);

    WAIT_UNTIL_POLISHED;

    // Flick half an item to the side, to force one extra row and column to load before we start.
    // This will make things less complicated below, when checking how many times the items
    // have been reused (all items will then report the same number).
    tableView->setContentX(delegateWidth / 2);
    tableView->setContentY(delegateHeight / 2);
    QCOMPARE(tableViewPrivate->tableModel->poolSize(), 0);

    // Some items have already been pooled and reused after we moved the content view, because
    // we preload one extra row and column at start-up. So reset the count-properties back to 0
    // before we continue.
    for (auto fxItem : tableViewPrivate->loadedItems) {
        fxItem->item->setProperty("pooledCount", 0);
        fxItem->item->setProperty("reusedCount", 0);
    }

    const int visibleColumnCount = tableViewPrivate->loadedColumns.count();
    const int visibleRowCount = tableViewPrivate->loadedRows.count();
    const int delegateCountAfterInit = view->rootObject()->property(kDelegatesCreatedCountProp).toInt();

    for (int column = 1; column <= (visibleColumnCount * pageFlickCount); ++column) {
        // Flick columns to the left (and add one pixel to ensure the left column is completely out)
        tableView->setContentX((delegateWidth * column) + 1);
        // Check that the number of delegate items created so far is what we expect.
        const int delegatesCreatedCount = view->rootObject()->property(kDelegatesCreatedCountProp).toInt();
        int expectedCount = delegateCountAfterInit + (reuseItems ? 0 : visibleRowCount * column);
        QCOMPARE(delegatesCreatedCount, expectedCount);
    }

    // Check that each delegate item has been reused as many times
    // as we have flicked pages (if reuse is enabled).
    for (auto fxItem : tableViewPrivate->loadedItems) {
        int pooledCount = fxItem->item->property("pooledCount").toInt();
        int reusedCount = fxItem->item->property("reusedCount").toInt();
        if (reuseItems) {
            QCOMPARE(pooledCount, pageFlickCount);
            QCOMPARE(reusedCount, pageFlickCount);
        } else {
            QCOMPARE(pooledCount, 0);
            QCOMPARE(reusedCount, 0);
        }
    }
}

void tst_QQuickTableView::checkIfDelegatesAreReusedAsymmetricTableSize()
{
    // Check that we end up reusing all delegate items while flicking, also if the table contain
    // more columns than rows. In that case, if we flick out a whole row, we'll move a lot of
    // items into the pool. And if we then start flicking in columns, we'll only reuse a few of
    // them for each column. Still, we don't want the pool to release the superfluous items after
    // each load, since they are still in circulation and will be needed once we flick in a new
    // row at the end of the test.
    LOAD_TABLEVIEW("countingtableview.qml");

    const int columnCount = 20;
    const int rowCount = 2;
    const qreal delegateWidth = tableView->width() / columnCount;
    const qreal delegateHeight = (tableView->height() / rowCount) + 10;

    auto model = TestModelAsVariant(100, 100);
    tableView->setModel(model);

    // Let the height of each row be much bigger than the width of each column.
    view->rootObject()->setProperty("delegateWidth", delegateWidth);
    view->rootObject()->setProperty("delegateHeight", delegateHeight);

    WAIT_UNTIL_POLISHED;

    auto initialTopLeftItem = tableViewPrivate->loadedTableItem(QPoint(0, 0))->item;
    QVERIFY(initialTopLeftItem);
    int pooledCount = initialTopLeftItem->property("pooledCount").toInt();
    int reusedCount = initialTopLeftItem->property("reusedCount").toInt();
    QCOMPARE(pooledCount, 0);
    QCOMPARE(reusedCount, 0);

    // Flick half an item left+down, to force one extra row and column to load. By doing
    // so, we force the maximum number of rows and columns to show before we start the test.
    // This will make things less complicated below, when checking how many
    // times the items have been reused (all items will then report the same number).
    tableView->setContentX(delegateWidth * 0.5);
    tableView->setContentY(delegateHeight * 0.5);

    // Since we have flicked half a delegate to the left, the number of visible
    // columns is now one more than the column count were when we started the test.
    const int visibleColumnCount = tableViewPrivate->loadedColumns.count();
    QCOMPARE(visibleColumnCount, columnCount + 1);

    // We expect no items to have been pooled so far
    pooledCount = initialTopLeftItem->property("pooledCount").toInt();
    reusedCount = initialTopLeftItem->property("reusedCount").toInt();
    QCOMPARE(pooledCount, 0);
    QCOMPARE(reusedCount, 0);
    QCOMPARE(tableViewPrivate->tableModel->poolSize(), 0);

    // Flick one row out of view. This will move one whole row of items into the
    // pool without reusing them, since no new row is exposed at the bottom.
    tableView->setContentY(delegateHeight + 1);
    pooledCount = initialTopLeftItem->property("pooledCount").toInt();
    reusedCount = initialTopLeftItem->property("reusedCount").toInt();
    QCOMPARE(pooledCount, 1);
    QCOMPARE(reusedCount, 0);
    QCOMPARE(tableViewPrivate->tableModel->poolSize(), visibleColumnCount);

    const int delegateCountAfterInit = view->rootObject()->property(kDelegatesCreatedCountProp).toInt();

    // Start flicking in a lot of columns, and check that the created count stays the same
    for (int column = 1; column <= 10; ++column) {
        tableView->setContentX((delegateWidth * column) + 10);
        const int delegatesCreatedCount = view->rootObject()->property(kDelegatesCreatedCountProp).toInt();
        // Since we reuse items while flicking, the created count should stay the same
        QCOMPARE(delegatesCreatedCount, delegateCountAfterInit);
        // Since we flick out just as many columns as we flick in, the pool size should stay the same
        QCOMPARE(tableViewPrivate->tableModel->poolSize(), visibleColumnCount);
    }

    // Finally, flick one row back into view (but without flicking so far that we push the third
    // row out and into the pool). The pool should still contain the exact amount of items that
    // we had after we flicked the first row out. And this should be exactly the amount of items
    // needed to load the row back again. And this also means that the pool count should then return
    // back to 0.
    tableView->setContentY(delegateHeight - 1);
    const int delegatesCreatedCount = view->rootObject()->property(kDelegatesCreatedCountProp).toInt();
    QCOMPARE(delegatesCreatedCount, delegateCountAfterInit);
    QCOMPARE(tableViewPrivate->tableModel->poolSize(), 0);
}

void tst_QQuickTableView::checkContextProperties_data()
{
    QTest::addColumn<QVariant>("model");
    QTest::addColumn<bool>("reuseItems");

    auto stringList = QStringList();
    for (int i = 0; i < 100; ++i)
        stringList.append(QString::number(i));

    QTest::newRow("QAIM, reuse=false") << TestModelAsVariant(100, 100) << false;
    QTest::newRow("QAIM, reuse=true") << TestModelAsVariant(100, 100) << true;
    QTest::newRow("Number model, reuse=false") << QVariant::fromValue(100) << false;
    QTest::newRow("Number model, reuse=true") << QVariant::fromValue(100) << true;
    QTest::newRow("QStringList, reuse=false") << QVariant::fromValue(stringList) << false;
    QTest::newRow("QStringList, reuse=true") << QVariant::fromValue(stringList) << true;
}

void tst_QQuickTableView::checkContextProperties()
{
    // Check that the context properties of the delegate items
    // are what we expect while flicking, with or without item recycling.
    QFETCH(QVariant, model);
    QFETCH(bool, reuseItems);
    LOAD_TABLEVIEW("countingtableview.qml");

    const qreal delegateWidth = 100;
    const qreal delegateHeight = 50;
    const int rowCount = 100;
    const int pageFlickCount = 3;

    tableView->setModel(model);
    tableView->setReuseItems(reuseItems);

    WAIT_UNTIL_POLISHED;

    const int visibleRowCount = qMin(tableView->rows(), qCeil(tableView->height() / delegateHeight));
    const int visibleColumnCount = qMin(tableView->columns(), qCeil(tableView->width() / delegateWidth));

    for (int row = 1; row <= (visibleRowCount * pageFlickCount); ++row) {
        // Flick rows up
        tableView->setContentY((delegateHeight * row) + (delegateHeight / 2));
        tableView->polish();

        WAIT_UNTIL_POLISHED;

        for (int col = 0; col < visibleColumnCount; ++col) {
            const auto item = tableViewPrivate->loadedTableItem(QPoint(col, row))->item;
            const auto context = qmlContext(item.data());
            const int contextIndex = context->contextProperty("index").toInt();
            const int contextRow = context->contextProperty("row").toInt();
            const int contextColumn = context->contextProperty("column").toInt();
            const QString contextModelData = context->contextProperty("modelData").toString();

            QCOMPARE(contextIndex, row + (col * rowCount));
            QCOMPARE(contextRow, row);
            QCOMPARE(contextColumn, col);
            QCOMPARE(contextModelData, QStringLiteral("%1").arg(row));
        }
    }
}

void tst_QQuickTableView::checkContextPropertiesQQmlListProperyModel_data()
{
    QTest::addColumn<bool>("reuseItems");

    QTest::newRow("reuse=false") << false;
    QTest::newRow("reuse=true") << true;
}

void tst_QQuickTableView::checkContextPropertiesQQmlListProperyModel()
{
    // Check that the context properties of the delegate items
    // are what we expect while flicking, with or without item recycling.
    // This test hard-codes the model to be a QQmlListPropertyModel from
    // within the qml file.
    QFETCH(bool, reuseItems);
    LOAD_TABLEVIEW("qqmllistpropertymodel.qml");

    const qreal delegateWidth = 100;
    const qreal delegateHeight = 50;
    const int rowCount = 100;
    const int pageFlickCount = 3;

    tableView->setReuseItems(reuseItems);
    tableView->polish();

    WAIT_UNTIL_POLISHED;

    const int visibleRowCount = qMin(tableView->rows(), qCeil(tableView->height() / delegateHeight));
    const int visibleColumnCount = qMin(tableView->columns(), qCeil(tableView->width() / delegateWidth));

    for (int row = 1; row <= (visibleRowCount * pageFlickCount); ++row) {
        // Flick rows up
        tableView->setContentY((delegateHeight * row) + (delegateHeight / 2));
        tableView->polish();

        WAIT_UNTIL_POLISHED;

        for (int col = 0; col < visibleColumnCount; ++col) {
            const auto item = tableViewPrivate->loadedTableItem(QPoint(col, row))->item;
            const auto context = qmlContext(item.data());
            const int contextIndex = context->contextProperty("index").toInt();
            const int contextRow = context->contextProperty("row").toInt();
            const int contextColumn = context->contextProperty("column").toInt();
            const QObject *contextModelData = qvariant_cast<QObject *>(context->contextProperty("modelData"));
            const QString modelDataProperty = contextModelData->property("someCustomProperty").toString();

            QCOMPARE(contextIndex, row + (col * rowCount));
            QCOMPARE(contextRow, row);
            QCOMPARE(contextColumn, col);
            QCOMPARE(modelDataProperty, QStringLiteral("%1").arg(row));
        }
    }
}

void tst_QQuickTableView::checkRowAndColumnChangedButNotIndex()
{
    // Check that context row and column changes even if the index stays the
    // same when the item is reused. This can happen in rare cases if the item
    // is first used at e.g (row 1, col 0), but then reused at (row 0, col 1)
    // while the model has changed row count in-between.
    LOAD_TABLEVIEW("checkrowandcolumnnotchanged.qml");

    TestModel model(2, 1);
    tableView->setModel(QVariant::fromValue(&model));

    WAIT_UNTIL_POLISHED;

    model.removeRow(1);
    model.insertColumn(1);
    tableView->forceLayout();

    const auto item = tableViewPrivate->loadedTableItem(QPoint(1, 0))->item;
    const auto context = qmlContext(item.data());
    const int contextIndex = context->contextProperty("index").toInt();
    const int contextRow = context->contextProperty("row").toInt();
    const int contextColumn = context->contextProperty("column").toInt();

    QCOMPARE(contextIndex, 1);
    QCOMPARE(contextRow, 0);
    QCOMPARE(contextColumn, 1);
}

void tst_QQuickTableView::checkChangingModelFromDelegate()
{
    // Check that we don't restart a rebuild of the table
    // while we're in the middle of rebuilding it from before
    LOAD_TABLEVIEW("changemodelfromdelegate.qml");

    // Set addRowFromDelegate. This will trigger the QML code to add a new
    // row and call forceLayout(). When TableView instantiates the first
    // delegate in the new row, the Component.onCompleted handler will try to
    // add a new row. But since we're currently rebuilding, this should be
    // scheduled for later.
    view->rootObject()->setProperty("addRowFromDelegate", true);

    // We now expect two rows in the table, one more than initially
    QCOMPARE(tableViewPrivate->tableSize.height(), 2);
    QCOMPARE(tableViewPrivate->loadedRows.count(), 2);

    // And since the QML code tried to add another row as well, we
    // expect rebuildScheduled to be true, and a polish event to be pending.
    QVERIFY(tableViewPrivate->scheduledRebuildOptions);
    QCOMPARE(tableViewPrivate->polishScheduled, true);
    WAIT_UNTIL_POLISHED;

    // After handling the polish event, we expect also the third row to now be added
    QCOMPARE(tableViewPrivate->tableSize.height(), 3);
    QCOMPARE(tableViewPrivate->loadedRows.count(), 3);
}

void tst_QQuickTableView::checkRebuildViewportOnly()
{
    // Check that we only rebuild from the current top-left cell
    // when you add or remove rows and columns. There should be
    // no need to do a rebuild from scratch in such cases.
    LOAD_TABLEVIEW("countingtableview.qml");

    const char *propName = "delegatesCreatedCount";
    const qreal delegateWidth = 100;
    const qreal delegateHeight = 50;

    TestModel model(100, 100);
    tableView->setModel(QVariant::fromValue(&model));

    WAIT_UNTIL_POLISHED;

    // Flick to row/column 50, 50
    tableView->setContentX(delegateWidth * 50);
    tableView->setContentY(delegateHeight * 50);

    // Set reuse items to false, just to make it easier to
    // check the number of items created during a rebuild.
    tableView->setReuseItems(false);
    const int itemCountBeforeRebuild = tableViewPrivate->loadedItems.count();

    // Since all cells have the same size, we expect that we end up creating
    // the same amount of items that were already showing before, even after
    // adding or removing rows and columns.
    view->rootObject()->setProperty(propName, 0);
    model.insertRow(51);
    WAIT_UNTIL_POLISHED;
    int countAfterRebuild = view->rootObject()->property(propName).toInt();
    QCOMPARE(countAfterRebuild, itemCountBeforeRebuild);

    view->rootObject()->setProperty(propName, 0);
    model.removeRow(51);
    WAIT_UNTIL_POLISHED;
    countAfterRebuild = view->rootObject()->property(propName).toInt();
    QCOMPARE(countAfterRebuild, itemCountBeforeRebuild);

    view->rootObject()->setProperty(propName, 0);
    model.insertColumn(51);
    WAIT_UNTIL_POLISHED;
    countAfterRebuild = view->rootObject()->property(propName).toInt();
    QCOMPARE(countAfterRebuild, itemCountBeforeRebuild);

    view->rootObject()->setProperty(propName, 0);
    model.removeColumn(51);
    WAIT_UNTIL_POLISHED;
    countAfterRebuild = view->rootObject()->property(propName).toInt();
    QCOMPARE(countAfterRebuild, itemCountBeforeRebuild);
}

void tst_QQuickTableView::useDelegateChooserWithoutDefault()
{
    // Check that the application issues a warning (but doesn't e.g
    // crash) if the delegate chooser doesn't cover all cells
    QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*failed"));
    LOAD_TABLEVIEW("usechooserwithoutdefault.qml");
    auto model = TestModelAsVariant(2, 1);
    tableView->setModel(model);
    WAIT_UNTIL_POLISHED;
};

void tst_QQuickTableView::checkTableviewInsideAsyncLoader()
{
    // Check that you can put a TableView inside an async Loader, and
    // that the delegate items are created before the loader is ready.
    LOAD_TABLEVIEW_ASYNC("asyncplain.qml");

    // At this point the Loader has finished
    QCOMPARE(loader->status(), QQuickLoader::Ready);

    // Check that TableView has finished building
    QVERIFY(!tableViewPrivate->scheduledRebuildOptions);
    QCOMPARE(tableViewPrivate->rebuildState, QQuickTableViewPrivate::RebuildState::Done);

    // Check that all expected delegate items have been loaded
    const qreal delegateWidth = 100;
    const qreal delegateHeight = 50;
    int expectedColumns = qCeil(tableView->width() / delegateWidth);
    int expectedRows = qCeil(tableView->height() / delegateHeight);
    QCOMPARE(tableViewPrivate->loadedColumns.count(), expectedColumns);
    QCOMPARE(tableViewPrivate->loadedRows.count(), expectedRows);

    // Check that the loader was still in a loading state while TableView was creating
    // delegate items. If we delayed creating delegate items until we got the first
    // updatePolish() callback in QQuickTableView, this would not be the case.
    auto statusWhenDelegate0_0Completed = qvariant_cast<QQuickLoader::Status>(
                loader->item()->property("statusWhenDelegate0_0Created"));
    auto statusWhenDelegate5_5Completed = qvariant_cast<QQuickLoader::Status>(
                loader->item()->property("statusWhenDelegate5_5Created"));
    QCOMPARE(statusWhenDelegate0_0Completed, QQuickLoader::Loading);
    QCOMPARE(statusWhenDelegate5_5Completed, QQuickLoader::Loading);

    // Check that TableView had a valid geometry when we started to build. If the build
    // was started too early (e.g upon QQuickTableView::componentComplete), width and
    // height would still be 0 since the bindings would not have been evaluated yet.
    qreal width = loader->item()->property("tableViewWidthWhileBuilding").toReal();
    qreal height = loader->item()->property("tableViewHeightWhileBuilding").toReal();
    QVERIFY(width > 0);
    QVERIFY(height > 0);
};

#define INT_LIST(indices) QVariant::fromValue(QList<int>() << indices)

void tst_QQuickTableView::hideRowsAndColumns_data()
{
    QTest::addColumn<QVariant>("rowsToHide");
    QTest::addColumn<QVariant>("columnsToHide");

    const auto emptyList = QVariant::fromValue(QList<int>());

    // Hide rows
    QTest::newRow("first") << INT_LIST(0) << emptyList;
    QTest::newRow("middle 1") << INT_LIST(1) << emptyList;
    QTest::newRow("middle 3") << INT_LIST(3) << emptyList;
    QTest::newRow("last") << INT_LIST(4) << emptyList;

    QTest::newRow("subsequent 0,1") << INT_LIST(0 << 1) << emptyList;
    QTest::newRow("subsequent 1,2") << INT_LIST(1 << 2) << emptyList;
    QTest::newRow("subsequent 3,4") << INT_LIST(3 << 4) << emptyList;

    QTest::newRow("all but first") << INT_LIST(1 << 2 << 3 << 4) << emptyList;
    QTest::newRow("all but last") << INT_LIST(0 << 1 << 2 << 3) << emptyList;
    QTest::newRow("all but middle") << INT_LIST(0 << 1 << 3 << 4) << emptyList;

    // Hide columns
    QTest::newRow("first") << emptyList << INT_LIST(0);
    QTest::newRow("middle 1") << emptyList << INT_LIST(1);
    QTest::newRow("middle 3") << emptyList << INT_LIST(3);
    QTest::newRow("last") << emptyList << INT_LIST(4);

    QTest::newRow("subsequent 0,1") << emptyList << INT_LIST(0 << 1);
    QTest::newRow("subsequent 1,2") << emptyList << INT_LIST(1 << 2);
    QTest::newRow("subsequent 3,4") << emptyList << INT_LIST(3 << 4);

    QTest::newRow("all but first") << emptyList << INT_LIST(1 << 2 << 3 << 4);
    QTest::newRow("all but last") << emptyList << INT_LIST(0 << 1 << 2 << 3);
    QTest::newRow("all but middle") << emptyList << INT_LIST(0 << 1 << 3 << 4);

    // Hide both rows and columns at the same time
    QTest::newRow("first") << INT_LIST(0) << INT_LIST(0);
    QTest::newRow("middle 1") << INT_LIST(1) << INT_LIST(1);
    QTest::newRow("middle 3") << INT_LIST(3) << INT_LIST(3);
    QTest::newRow("last") << INT_LIST(4) << INT_LIST(4);

    QTest::newRow("subsequent 0,1") << INT_LIST(0 << 1) << INT_LIST(0 << 1);
    QTest::newRow("subsequent 1,2") << INT_LIST(1 << 2) << INT_LIST(1 << 2);
    QTest::newRow("subsequent 3,4") << INT_LIST(3 << 4) << INT_LIST(3 << 4);

    QTest::newRow("all but first") << INT_LIST(1 << 2 << 3 << 4) << INT_LIST(1 << 2 << 3 << 4);
    QTest::newRow("all but last") << INT_LIST(0 << 1 << 2 << 3) << INT_LIST(0 << 1 << 2 << 3);
    QTest::newRow("all but middle") << INT_LIST(0 << 1 << 3 << 4) << INT_LIST(0 << 1 << 3 << 4);

    // Hide all rows and columns
    QTest::newRow("all") << INT_LIST(0 << 1 << 2 << 3 << 4) << INT_LIST(0 << 1 << 2 << 3 << 4);
}

void tst_QQuickTableView::hideRowsAndColumns()
{
    // Check that you can hide the first row (corner case)
    // and that we load the other columns as expected.
    QFETCH(QVariant, rowsToHide);
    QFETCH(QVariant, columnsToHide);
    LOAD_TABLEVIEW("hiderowsandcolumns.qml");

    const QList<int> rowsToHideList = qvariant_cast<QList<int>>(rowsToHide);
    const QList<int> columnsToHideList = qvariant_cast<QList<int>>(columnsToHide);
    const int modelSize = 5;
    auto model = TestModelAsVariant(modelSize, modelSize);
    view->rootObject()->setProperty("rowsToHide", rowsToHide);
    view->rootObject()->setProperty("columnsToHide", columnsToHide);

    tableView->setModel(model);

    WAIT_UNTIL_POLISHED;

    const int expectedRowCount = modelSize - rowsToHideList.count();
    const int expectedColumnCount = modelSize - columnsToHideList.count();
    QCOMPARE(tableViewPrivate->loadedRows.count(), expectedRowCount);
    QCOMPARE(tableViewPrivate->loadedColumns.count(), expectedColumnCount);

    for (const int row : tableViewPrivate->loadedRows.keys())
        QVERIFY(!rowsToHideList.contains(row));

    for (const int column : tableViewPrivate->loadedColumns.keys())
        QVERIFY(!columnsToHideList.contains(column));
}

void tst_QQuickTableView::checkThatRevisionedPropertiesCannotBeUsedInOldImports()
{
    // Check that if you use a QQmlAdaptorModel together with a Repeater, the
    // revisioned context properties 'row' and 'column' are not accessible.
    LOAD_TABLEVIEW("checkmodelpropertyrevision.qml");
    const int resolvedRow = view->rootObject()->property("resolvedDelegateRow").toInt();
    const int resolvedColumn = view->rootObject()->property("resolvedDelegateColumn").toInt();
    QCOMPARE(resolvedRow, 42);
    QCOMPARE(resolvedColumn, 42);
}

void tst_QQuickTableView::checkSyncView_rootView_data()
{
    QTest::addColumn<qreal>("flickToPos");

    QTest::newRow("pos:110") << 110.;
    QTest::newRow("pos:2010") << 2010.;
}

void tst_QQuickTableView::checkSyncView_rootView()
{
    // Check that if you flick on the root tableview (the view that has
    // no other view as syncView), all the other tableviews will sync
    // their content view position according to their syncDirection flag.
    QFETCH(qreal, flickToPos);
    LOAD_TABLEVIEW("syncviewsimple.qml");
    GET_QML_TABLEVIEW(tableViewH);
    GET_QML_TABLEVIEW(tableViewV);
    GET_QML_TABLEVIEW(tableViewHV);
    QQuickTableView *views[] = {tableViewH, tableViewV, tableViewHV};

    auto model = TestModelAsVariant(100, 100);

    tableView->setModel(model);
    for (auto view : views)
        view->setModel(model);

    tableView->setContentX(flickToPos);
    tableView->setContentY(flickToPos);

    WAIT_UNTIL_POLISHED;

    // Check that geometry properties are mirrored
    QCOMPARE(tableViewH->columnSpacing(), tableView->columnSpacing());
    QCOMPARE(tableViewH->rowSpacing(), 0);
    QCOMPARE(tableViewH->contentWidth(), tableView->contentWidth());
    QCOMPARE(tableViewV->columnSpacing(), 0);
    QCOMPARE(tableViewV->rowSpacing(), tableView->rowSpacing());
    QCOMPARE(tableViewV->contentHeight(), tableView->contentHeight());

    // Check that viewport is in sync after the flick
    QCOMPARE(tableView->contentX(), flickToPos);
    QCOMPARE(tableView->contentY(), flickToPos);
    QCOMPARE(tableViewH->contentX(), tableView->contentX());
    QCOMPARE(tableViewH->contentY(), 0);
    QCOMPARE(tableViewV->contentX(), 0);
    QCOMPARE(tableViewV->contentY(), tableView->contentY());
    QCOMPARE(tableViewHV->contentX(), tableView->contentX());
    QCOMPARE(tableViewHV->contentY(), tableView->contentY());

    // Check that topLeft cell is in sync after the flick
    QCOMPARE(tableViewHPrivate->leftColumn(), tableViewPrivate->leftColumn());
    QCOMPARE(tableViewHPrivate->rightColumn(), tableViewPrivate->rightColumn());
    QCOMPARE(tableViewHPrivate->topRow(), 0);
    QCOMPARE(tableViewVPrivate->leftColumn(), 0);
    QCOMPARE(tableViewVPrivate->topRow(), tableViewPrivate->topRow());
    QCOMPARE(tableViewHVPrivate->leftColumn(), tableViewPrivate->leftColumn());
    QCOMPARE(tableViewHVPrivate->topRow(), tableViewPrivate->topRow());

    // Check that the geometry of the tables are in sync after the flick
    QCOMPARE(tableViewHPrivate->loadedTableOuterRect.left(), tableViewPrivate->loadedTableOuterRect.left());
    QCOMPARE(tableViewHPrivate->loadedTableOuterRect.right(), tableViewPrivate->loadedTableOuterRect.right());
    QCOMPARE(tableViewHPrivate->loadedTableOuterRect.top(), 0);

    QCOMPARE(tableViewVPrivate->loadedTableOuterRect.top(), tableViewPrivate->loadedTableOuterRect.top());
    QCOMPARE(tableViewVPrivate->loadedTableOuterRect.bottom(), tableViewPrivate->loadedTableOuterRect.bottom());
    QCOMPARE(tableViewVPrivate->loadedTableOuterRect.left(), 0);

    QCOMPARE(tableViewHVPrivate->loadedTableOuterRect, tableViewPrivate->loadedTableOuterRect);
}

void tst_QQuickTableView::checkSyncView_childViews_data()
{
    QTest::addColumn<int>("viewIndexToFlick");
    QTest::addColumn<qreal>("flickToPos");

    QTest::newRow("tableViewH, pos:100") << 0 << 100.;
    QTest::newRow("tableViewV, pos:100") << 1 << 100.;
    QTest::newRow("tableViewHV, pos:100") << 2 << 100.;
    QTest::newRow("tableViewH, pos:2000") << 0 << 2000.;
    QTest::newRow("tableViewV, pos:2000") << 1 << 2000.;
    QTest::newRow("tableViewHV, pos:2000") << 2 << 2000.;
}

void tst_QQuickTableView::checkSyncView_childViews()
{
    // Check that if you flick on a tableview that has a syncView, the
    // syncView will move to the new position as well, which will also
    // recursivly move all other connected child views of the syncView.
    QFETCH(int, viewIndexToFlick);
    QFETCH(qreal, flickToPos);
    LOAD_TABLEVIEW("syncviewsimple.qml");
    GET_QML_TABLEVIEW(tableViewH);
    GET_QML_TABLEVIEW(tableViewV);
    GET_QML_TABLEVIEW(tableViewHV);
    QQuickTableView *views[] = {tableViewH, tableViewV, tableViewHV};
    QQuickTableView *viewToFlick = views[viewIndexToFlick];
    QQuickTableViewPrivate *viewToFlickPrivate = QQuickTableViewPrivate::get(viewToFlick);

    auto model = TestModelAsVariant(100, 100);

    tableView->setModel(model);
    for (auto view : views)
        view->setModel(model);

    viewToFlick->setContentX(flickToPos);
    viewToFlick->setContentY(flickToPos);

    WAIT_UNTIL_POLISHED;

    // The view the user flicks on can always be flicked in both directions
    // (unless is has a flickingDirection set, which is not the case here).
    QCOMPARE(viewToFlick->contentX(), flickToPos);
    QCOMPARE(viewToFlick->contentY(), flickToPos);

    // The root view (tableView) will move in sync according
    // to the syncDirection of the view being flicked.
    if (viewToFlick->syncDirection() & Qt::Horizontal) {
        QCOMPARE(tableView->contentX(), flickToPos);
        QCOMPARE(tableViewPrivate->leftColumn(), viewToFlickPrivate->leftColumn());
        QCOMPARE(tableViewPrivate->rightColumn(), viewToFlickPrivate->rightColumn());
        QCOMPARE(tableViewPrivate->loadedTableOuterRect.left(), viewToFlickPrivate->loadedTableOuterRect.left());
        QCOMPARE(tableViewPrivate->loadedTableOuterRect.right(), viewToFlickPrivate->loadedTableOuterRect.right());
    } else {
        QCOMPARE(tableView->contentX(), 0);
        QCOMPARE(tableViewPrivate->leftColumn(), 0);
        QCOMPARE(tableViewPrivate->loadedTableOuterRect.left(), 0);
    }

    if (viewToFlick->syncDirection() & Qt::Vertical) {
        QCOMPARE(tableView->contentY(), flickToPos);
        QCOMPARE(tableViewPrivate->topRow(), viewToFlickPrivate->topRow());
        QCOMPARE(tableViewPrivate->bottomRow(), viewToFlickPrivate->bottomRow());
        QCOMPARE(tableViewPrivate->loadedTableOuterRect.top(), viewToFlickPrivate->loadedTableOuterRect.top());
        QCOMPARE(tableViewPrivate->loadedTableOuterRect.bottom(), viewToFlickPrivate->loadedTableOuterRect.bottom());
    } else {
        QCOMPARE(tableView->contentY(), 0);
        QCOMPARE(tableViewPrivate->topRow(), 0);
        QCOMPARE(tableViewPrivate->loadedTableOuterRect.top(), 0);
    }

    // The other views should continue to stay in sync with
    // the root view, unless it was the view being flicked.
    if (viewToFlick != tableViewH) {
        QCOMPARE(tableViewH->contentX(), tableView->contentX());
        QCOMPARE(tableViewH->contentY(), 0);
        QCOMPARE(tableViewHPrivate->leftColumn(), tableViewPrivate->leftColumn());
        QCOMPARE(tableViewHPrivate->rightColumn(), tableViewPrivate->rightColumn());
        QCOMPARE(tableViewHPrivate->loadedTableOuterRect.left(), tableViewPrivate->loadedTableOuterRect.left());
        QCOMPARE(tableViewHPrivate->loadedTableOuterRect.right(), tableViewPrivate->loadedTableOuterRect.right());
        QCOMPARE(tableViewHPrivate->topRow(), 0);
        QCOMPARE(tableViewHPrivate->loadedTableOuterRect.top(), 0);
    }

    if (viewToFlick != tableViewV) {
        QCOMPARE(tableViewV->contentX(), 0);
        QCOMPARE(tableViewV->contentY(), tableView->contentY());
        QCOMPARE(tableViewVPrivate->topRow(), tableViewPrivate->topRow());
        QCOMPARE(tableViewVPrivate->bottomRow(), tableViewPrivate->bottomRow());
        QCOMPARE(tableViewVPrivate->loadedTableOuterRect.top(), tableViewPrivate->loadedTableOuterRect.top());
        QCOMPARE(tableViewVPrivate->loadedTableOuterRect.bottom(), tableViewPrivate->loadedTableOuterRect.bottom());
        QCOMPARE(tableViewVPrivate->leftColumn(), 0);
        QCOMPARE(tableViewVPrivate->loadedTableOuterRect.left(), 0);
    }

    if (viewToFlick != tableViewHV) {
        QCOMPARE(tableViewHV->contentX(), tableView->contentX());
        QCOMPARE(tableViewHV->contentY(), tableView->contentY());
        QCOMPARE(tableViewHVPrivate->leftColumn(), tableViewPrivate->leftColumn());
        QCOMPARE(tableViewHVPrivate->rightColumn(), tableViewPrivate->rightColumn());
        QCOMPARE(tableViewHVPrivate->topRow(), tableViewPrivate->topRow());
        QCOMPARE(tableViewHVPrivate->bottomRow(), tableViewPrivate->bottomRow());
        QCOMPARE(tableViewHVPrivate->loadedTableOuterRect, tableViewPrivate->loadedTableOuterRect);
    }
}

void tst_QQuickTableView::checkSyncView_differentSizedModels()
{
    // Check that you can have two tables in a syncView relation, where
    // the sync "child" has fewer rows/columns than the syncView. In that
    // case, it will be possible to flick the syncView further out than
    // the child have rows/columns to follow. This causes some extra
    // challenges for TableView to ensure that they are still kept in
    // sync once you later flick the syncView back to a point where both
    // tables ends up visible. This test will check this sitiation.
    LOAD_TABLEVIEW("syncviewsimple.qml");
    GET_QML_TABLEVIEW(tableViewH);
    GET_QML_TABLEVIEW(tableViewV);
    GET_QML_TABLEVIEW(tableViewHV);

    auto tableViewModel = TestModelAsVariant(100, 100);
    auto tableViewHModel = TestModelAsVariant(100, 50);
    auto tableViewVModel = TestModelAsVariant(50, 100);
    auto tableViewHVModel = TestModelAsVariant(5, 5);

    tableView->setModel(tableViewModel);
    tableViewH->setModel(tableViewHModel);
    tableViewV->setModel(tableViewVModel);
    tableViewHV->setModel(tableViewHVModel);

    WAIT_UNTIL_POLISHED;

    // Flick far out, beyond the smaller tables, which will
    // also force a rebuild (and as such, cause layout properties
    // like average cell width to be temporarily out of sync).
    tableView->setContentX(5000);
    QVERIFY(tableViewPrivate->scheduledRebuildOptions);

    WAIT_UNTIL_POLISHED;

    // Check that the smaller tables are now flicked out of view
    qreal leftEdge = tableViewPrivate->loadedTableOuterRect.left();
    QVERIFY(tableViewHPrivate->loadedTableOuterRect.right() < leftEdge);
    QVERIFY(tableViewHVPrivate->loadedTableOuterRect.right() < leftEdge);

    // Flick slowly back so that we don't trigger a rebuild (since
    // we want to check that we stay in sync also when not rebuilding).
    while (tableView->contentX() > 200) {
        tableView->setContentX(tableView->contentX() - 200);
        QVERIFY(!tableViewPrivate->rebuildOptions);
        QVERIFY(!tableViewPrivate->polishScheduled);
    }

    leftEdge = tableViewPrivate->loadedTableOuterRect.left();
    const int leftColumn = tableViewPrivate->leftColumn();
    QCOMPARE(tableViewHPrivate->loadedTableOuterRect.left(), leftEdge);
    QCOMPARE(tableViewHPrivate->leftColumn(), leftColumn);

    // Because the tableView was fast flicked and then slowly flicked back, the
    // left column is now 49, which is actually far too high, since we're almost
    // at the beginning of the content view. But this "miscalculation" is expected
    // when the column widths are increasing for each column, like they do in this
    // test. In that case, the algorithm that predicts where each column should end
    // up gets slightly confused. Anyway, check that tableViewHV, that has only
    // 5 columns, is not showing any columns, since it should always stay in sync with
    // syncView regardless of the content view position.
    QVERIFY(tableViewHVPrivate->loadedColumns.isEmpty());
}

void tst_QQuickTableView::checkSyncView_connect_late_data()
{
    QTest::addColumn<qreal>("flickToPos");

    QTest::newRow("pos:110") << 110.;
    QTest::newRow("pos:2010") << 2010.;
}

void tst_QQuickTableView::checkSyncView_connect_late()
{
    // Check that if you assign a syncView to a TableView late, and
    // after the views have been flicked around, they will still end up in sync.
    QFETCH(qreal, flickToPos);
    LOAD_TABLEVIEW("syncviewsimple.qml");
    GET_QML_TABLEVIEW(tableViewH);
    GET_QML_TABLEVIEW(tableViewV);
    GET_QML_TABLEVIEW(tableViewHV);
    QQuickTableView *views[] = {tableViewH, tableViewV, tableViewHV};

    auto model = TestModelAsVariant(100, 100);

    tableView->setModel(model);

    // Start with no syncView connections
    for (auto view : views) {
        view->setSyncView(nullptr);
        view->setModel(model);
    }

    WAIT_UNTIL_POLISHED;

    tableView->setContentX(flickToPos);
    tableView->setContentY(flickToPos);

    WAIT_UNTIL_POLISHED;

    // Check that viewport is not in sync after the flick
    QCOMPARE(tableView->contentX(), flickToPos);
    QCOMPARE(tableView->contentY(), flickToPos);
    QCOMPARE(tableViewH->contentX(), 0);
    QCOMPARE(tableViewH->contentY(), 0);
    QCOMPARE(tableViewV->contentX(), 0);
    QCOMPARE(tableViewV->contentY(), 0);
    QCOMPARE(tableViewHV->contentX(), 0);
    QCOMPARE(tableViewHV->contentY(), 0);

    // Assign the syncView late. This should make
    // all the views end up in sync.
    for (auto view : views) {
        view->setSyncView(tableView);
        WAIT_UNTIL_POLISHED_ARG(view);
    }

    // Check that geometry properties are mirrored
    QCOMPARE(tableViewH->columnSpacing(), tableView->columnSpacing());
    QCOMPARE(tableViewH->rowSpacing(), 0);
    QCOMPARE(tableViewH->contentWidth(), tableView->contentWidth());
    QCOMPARE(tableViewV->columnSpacing(), 0);
    QCOMPARE(tableViewV->rowSpacing(), tableView->rowSpacing());
    QCOMPARE(tableViewV->contentHeight(), tableView->contentHeight());

    // Check that viewport is in sync after the flick
    QCOMPARE(tableView->contentX(), flickToPos);
    QCOMPARE(tableView->contentY(), flickToPos);
    QCOMPARE(tableViewH->contentX(), tableView->contentX());
    QCOMPARE(tableViewH->contentY(), 0);
    QCOMPARE(tableViewV->contentX(), 0);
    QCOMPARE(tableViewV->contentY(), tableView->contentY());
    QCOMPARE(tableViewHV->contentX(), tableView->contentX());
    QCOMPARE(tableViewHV->contentY(), tableView->contentY());

    // Check that topLeft cell is in sync after the flick
    QCOMPARE(tableViewHPrivate->leftColumn(), tableViewPrivate->leftColumn());
    QCOMPARE(tableViewHPrivate->rightColumn(), tableViewPrivate->rightColumn());
    QCOMPARE(tableViewHPrivate->topRow(), 0);
    QCOMPARE(tableViewVPrivate->leftColumn(), 0);
    QCOMPARE(tableViewVPrivate->topRow(), tableViewPrivate->topRow());
    QCOMPARE(tableViewHVPrivate->leftColumn(), tableViewPrivate->leftColumn());
    QCOMPARE(tableViewHVPrivate->topRow(), tableViewPrivate->topRow());

    // Check that the geometry of the tables are in sync after the flick
    QCOMPARE(tableViewHPrivate->loadedTableOuterRect.left(), tableViewPrivate->loadedTableOuterRect.left());
    QCOMPARE(tableViewHPrivate->loadedTableOuterRect.right(), tableViewPrivate->loadedTableOuterRect.right());
    QCOMPARE(tableViewHPrivate->loadedTableOuterRect.top(), 0);

    QCOMPARE(tableViewVPrivate->loadedTableOuterRect.top(), tableViewPrivate->loadedTableOuterRect.top());
    QCOMPARE(tableViewVPrivate->loadedTableOuterRect.bottom(), tableViewPrivate->loadedTableOuterRect.bottom());
    QCOMPARE(tableViewVPrivate->loadedTableOuterRect.left(), 0);

    QCOMPARE(tableViewHVPrivate->loadedTableOuterRect, tableViewPrivate->loadedTableOuterRect);

}

QTEST_MAIN(tst_QQuickTableView)

#include "tst_qquicktableview.moc"