summaryrefslogtreecommitdiffstats
path: root/tqtinterface/qt4/src/sql/tqdatatable.cpp
blob: 496da9dbd20a785d22920217e3dc125925cc61e9 (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
/****************************************************************************
**
** Implementation of TQDataTable class
**
** Created : 2000-11-03
**
** Copyright (C) 2005-2008 Trolltech ASA.  All rights reserved.
**
** This file is part of the sql module of the TQt GUI Toolkit.
**
** This file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the files LICENSE.GPL2
** and LICENSE.GPL3 included in the packaging of this file.
** Alternatively you may (at your option) use any later version
** of the GNU General Public License if such license has been
** publicly approved by Trolltech ASA (or its successors, if any)
** and the KDE Free TQt Foundation.
**
** Please review the following information to ensure GNU General
** Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/.
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** This file may be used under the terms of the Q Public License as
** defined by Trolltech ASA and appearing in the file LICENSE.TQPL
** included in the packaging of this file.  Licensees holding valid TQt
** Commercial licenses may use this file in accordance with the TQt
** Commercial License Agreement provided with the Software.
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted
** herein.
**
**********************************************************************/

#include "tqdatatable.h"

#ifndef TQT_NO_STQL_VIEW_WIDGETS

#include "tqsqldriver.h"
#include "tqsqleditorfactory.h"
#include "tqsqlpropertymap.h"
#include "tqapplication.h"
#include "tqlayout.h"
#include "tqpainter.h"
#include "tqpopupmenu.h"
#include "tqvaluelist.h"
#include "tqsqlmanager_p.h"
#include "tqdatetime.h"
#include "tqcursor.h"
#include "tqtimer.h"

//#define TQT_DEBUG_DATATABLE

class TQDataTablePrivate
{
public:
    TQDataTablePrivate()
	: nullTxtChanged( FALSE ),
	  haveAllRows( FALSE ),
	  continuousEdit( FALSE ),
	  editorFactory( 0 ),
	  propertyMap( 0 ),
	  editRow( -1 ),
	  editCol( -1 ),
	  insertRowLast( -1 ),
	  insertPreRows( -1 ),
	  editBuffer( 0 ),
	  cancelMode( FALSE ),
	  cancelInsert( FALSE ),
	  cancelUpdate( FALSE )
    {}
    ~TQDataTablePrivate() { if ( propertyMap ) delete propertyMap; }

    TQString nullTxt;
    bool nullTxtChanged;
    typedef TQValueList< uint > ColIndex;
    ColIndex colIndex;
    bool haveAllRows;
    bool continuousEdit;
    TQSqlEditorFactory* editorFactory;
    TQSqlPropertyMap* propertyMap;
    TQString trueTxt;
    Qt::DateFormat datefmt;
    TQString falseTxt;
    int editRow;
    int editCol;
    int insertRowLast;
    TQString insertHeaderLabelLast;
    int insertPreRows;
    TQSqlRecord* editBuffer;
    bool cancelMode;
    bool cancelInsert;
    bool cancelUpdate;
    int lastAt;
    TQString ftr;
    TQStringList srt;
    TQStringList fld;
    TQStringList fldLabel;
    TQValueList<int> fldWidth;
    TQValueList<TQIconSet> fldIcon;
    TQValueList<bool> fldHidden;
    TQSqlCursorManager cur;
    TQDataManager dat;
};

#ifdef TQT_DEBUG_DATATABLE
void qt_debug_buffer( const TQString& msg, TQSqlRecord* cursor )
{
    qDebug("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    qDebug(msg);
    for ( uint j = 0; j < cursor->count(); ++j ) {
	qDebug(cursor->field(j)->name() + " type:" + TQString(cursor->field(j)->value().typeName()) + " value:" + cursor->field(j)->value().toString() );
    }
}
#endif

/*!
    \enum TQDataTable::Refresh

    This enum describes the refresh options.

    \value RefreshData  refresh the data, i.e. read it from the database
    \value RefreshColumns  refresh the list of fields, e.g. the column headings
    \value RefreshAll  refresh both the data and the list of fields
*/


/*!
    \class TQDataTable tqdatatable.h
    \brief The TQDataTable class provides a flexible SQL table widget that supports browsing and editing.

    \ingroup database
    \mainclass
    \module sql

    TQDataTable supports various functions for presenting and editing
    SQL data from a \l TQSqlCursor in a table.

    If you want a to present your data in a form use TQDataBrowser, or
    for read-only forms, TQDataView.

    When displaying data, TQDataTable only retrieves data for visible
    rows. If the driver supports the 'query size' property the
    TQDataTable will have the correct number of rows and the vertical
    scrollbar will accurately reflect the number of rows displayed in
    proportion to the number of rows in the dataset. If the driver
    does not support the 'query size' property, rows are dynamically
    fetched from the database on an as-needed basis with the scrollbar
    becoming more accurate as the user scrolls down through the
    records. This allows extremely large queries to be displayed as
    quickly as possible, with minimum memory usage.

    TQDataTable inherits TQTable's API and extends it with functions to
    sort and filter the data and sort columns. See setSqlCursor(),
    setFilter(), setSort(), setSorting(), sortColumn() and refresh().

    When displaying editable cursors, cell editing will be enabled.
    (For more information on editable cursors, see \l TQSqlCursor).
    TQDataTable can be used to modify existing data and to add new
    records. When a user makes changes to a field in the table, the
    cursor's edit buffer is used. The table will not send changes in
    the edit buffer to the database until the user moves to a
    different record in the grid or presses Enter. Cell editing is
    initiated by pressing F2 (or right clicking and then clicking the
    appropriate popup menu item) and canceled by pressing Esc. If
    there is a problem updating or adding data, errors are handled
    automatically (see handleError() to change this behavior). Note
    that if autoEdit() is FALSE navigating to another record will
    cancel the insert or update.

    The user can be asked to confirm all edits with setConfirmEdits().
    For more precise control use setConfirmInsert(),
    setConfirmUpdate(), setConfirmDelete() and setConfirmCancels().
    Use setAutoEdit() to control the behaviour of the table when the
    user edits a record and then navigates. (Note that setAutoDelete()
    is unrelated; it is used to set whether the TQSqlCursor is deleted
    when the table is deleted.)

    Since the data table can perform edits, it must be able to
    uniquely identify every record so that edits are correctly
    applied. Because of this the underlying cursor must have a valid
    primary index to ensure that a unique record is inserted, updated
    or deleted within the database otherwise the database may be
    changed to an inconsistent state.

    TQDataTable creates editors using the default \l TQSqlEditorFactory.
    Different editor factories can be used by calling
    installEditorFactory(). A property map is used to map between the
    cell's value and the editor. You can use your own property map
    with installPropertyMap().

    The contents of a cell is available as a TQString with text() or as
    a TQVariant with value(). The current record is returned by
    currentRecord(). Use the tqfind() function to search for a string in
    the table.

    Editing actions can be applied programatically. For example, the
    insertCurrent() function reads the fields from the current record
    into the cursor and performs the insert. The updateCurrent() and
    deleteCurrent() functions perform similarly to update and delete
    the current record respectively.

    Columns in the table can be created automatically based on the
    cursor (see setSqlCursor()). Columns can be manipulated manually
    using addColumn(), removeColumn() and setColumn().

    The table automatically copies many of the properties of the
    cursor to format the display of data within cells (tqalignment,
    visibility, etc.). The cursor can be changed with setSqlCursor().
    The filter (see setFilter()) and sort defined within the table are
    used instead of the filter and sort set on the cursor. For sorting
    options see setSort(), sortColumn(), sortAscending() and
    sortDescending(). Note that sorting operations will not behave as
    expected if you are using a TQSqlSelectCursor because it uses
    user-defined SQL queries to obtain data.

    The text used to represent NULL, TRUE and FALSE values can be
    changed with setNullText(), setTrueText() and setFalseText()
    respectively. You can change the appearance of cells by
    reimplementing paintField().

    Whenever a new row is selected in the table the currentChanged()
    signal is emitted. The primeInsert() signal is emitted when an
    insert is initiated. The primeUpdate() and primeDelete() Q_SIGNALS
    are emitted when update and deletion are initiated respectively.
    Just before the database is updated a signal is emitted;
    beforeInsert(), beforeUpdate() or beforeDelete() as appropriate.

*/

/*!
    Constructs a data table which is a child of \a tqparent, called
    name \a name.
*/

TQDataTable::TQDataTable ( TQWidget * tqparent, const char * name )
    : TQTable( tqparent, name )
{
    init();
}

/*!
    Constructs a data table which is a child of \a tqparent, called name
    \a name using the cursor \a cursor.

    If \a autoPopulate is TRUE (the default is FALSE), columns are
    automatically created based upon the fields in the \a cursor
    record. Note that \a autoPopulate only governs the creation of
    columns; to load the cursor's data into the table use refresh().

    If the \a cursor is read-only, the table also becomes read-only.
    In addition, the table adopts the cursor's driver's definition for
    representing NULL values as strings.
*/

TQDataTable::TQDataTable ( TQSqlCursor* cursor, bool autoPopulate, TQWidget * tqparent, const char * name )
    : TQTable( tqparent, name )
{
    init();
    setSqlCursor( cursor, autoPopulate );
}

/*! \internal
*/


void TQDataTable::init()
{
    d = new TQDataTablePrivate();
    setAutoEdit( TRUE );
    setSelectionMode( SingleRow );
    setFocusStyle( FollowStyle );
    d->trueTxt = tr( "True" );
    d->falseTxt = tr( "False" );
    d->datefmt = Qt::LocalDate;
    reset();
    connect( this, TQT_SIGNAL( selectionChanged() ),
	     TQT_SLOT( updateCurrentSelection()));
}

/*!
    Destroys the object and frees any allocated resources.
*/

TQDataTable::~TQDataTable()
{
    delete d;
}


/*!
    Adds the next column to be displayed using the field \a fieldName,
    column label \a label, width \a width and iconset \a iconset.

    If \a label is specified, it is used as the column's header label,
    otherwise the field's display label is used when setSqlCursor() is
    called. The \a iconset is used to set the icon used by the column
    header; by default there is no icon.

    \sa setSqlCursor() refresh()
*/

void TQDataTable::addColumn( const TQString& fieldName,
			    const TQString& label,
			    int width,
			    const TQIconSet& iconset )
{
    d->fld += fieldName;
    d->fldLabel += label;
    d->fldIcon += iconset;
    d->fldWidth += width;
    d->fldHidden += FALSE;
}

/*!
    Sets the \a col column to display using the field \a fieldName,
    column label \a label, width \a width and iconset \a iconset.

    If \a label is specified, it is used as the column's header label,
    otherwise the field's display label is used when setSqlCursor() is
    called. The \a iconset is used to set the icon used by the column
    header; by default there is no icon.

    \sa setSqlCursor() refresh()
*/

void TQDataTable::setColumn( uint col, const TQString& fieldName,
			    const TQString& label,
			    int width,
			    const TQIconSet& iconset )
{
    d->fld[col]= fieldName;
    d->fldLabel[col] = label;
    d->fldIcon[col] = iconset;
    d->fldWidth[col] = width;
    d->fldHidden[col] = FALSE;
}

/*!
    Removes column \a col from the list of columns to be displayed. If
    \a col does not exist, nothing happens.

    \sa TQSqlField
*/

void TQDataTable::removeColumn( uint col )
{
    if ( d->fld.at( col ) != d->fld.end() ) {
	d->fld.remove( d->fld.at( col ) );
	d->fldLabel.remove( d->fldLabel.at( col ) );
	d->fldIcon.remove( d->fldIcon.at( col ) );
	d->fldWidth.remove( d->fldWidth.at( col ) );
	d->fldHidden.remove( d->fldHidden.at( col ) );
    }
}

/*!
    Sets the column \a col to the width \a w. Note that unlike TQTable
    the TQDataTable is not immediately redrawn, you must call
    refresh(TQDataTable::RefreshColumns)
    yourself.

    \sa refresh()
*/
void TQDataTable::setColumnWidth( int col, int w )
{
    if ( d->fldWidth.at( col ) != d->fldWidth.end() ) {
	d->fldWidth[col] = w;
    }
}

/*!
    Resizes column \a col so that the column width is wide enough to
    display the widest item the column tqcontains (including the column
    label). If the table's TQSqlCursor is not currently active, the
    cursor will be refreshed before the column width is calculated. Be
    aware that this function may be slow on tables that contain large
    result sets.
*/
void TQDataTable::adjustColumn( int col )
{
    TQSqlCursor * cur = sqlCursor();
    if ( !cur || cur->count() <= (uint)col )
	return;
    if ( !cur->isActive() ) {
	d->cur.refresh();
    }
    int oldRow = currentRow();
    int w = fontMetrics().width( horizontalHeader()->label( col ) + "W" );
    cur->seek( TQSql::BeforeFirst );
    while ( cur->next() ) {
	w = TQMAX( w, fontMetrics().width( fieldToString( cur->field( indexOf( col ) ) ) ) + 10 );
    }
    setColumnWidth( col, w );
    cur->seek( oldRow );
    refresh( RefreshColumns );
}

/*! \reimp
*/
void TQDataTable::setColumnStretchable( int col, bool s )
{
    if ( numCols() == 0 ) {
	refresh( RefreshColumns );
    }
    if ( numCols() > col ) {
	TQTable::setColumnStretchable( col, s );
    }
}

TQString TQDataTable::filter() const
{
    return d->cur.filter();
}

/*!
    \property TQDataTable::filter
    \brief the data filter for the data table

    The filter applies to the data shown in the table. To view data
    with a new filter, use refresh(). A filter string is an SQL WHERE
    clause without the WHERE keyword.

    There is no default filter.

    \sa sort()

*/

void TQDataTable::setFilter( const TQString& filter )
{
    d->cur.setFilter( filter );
}


/*!
    \property TQDataTable::sort
    \brief the data table's sort

    The table's sort affects the order in which data records are
    displayed in the table. To apply a sort, use refresh().

    When examining the sort property, a string list is returned with
    each item having the form 'fieldname order' (e.g., 'id ASC',
    'surname DESC').

    There is no default sort.

    Note that if you want to iterate over the sort list, you should
    iterate over a copy, e.g.
    \code
    TQStringList list = myDataTable.sort();
    TQStringList::Iterator it = list.begin();
    while( it != list.end() ) {
	myProcessing( *it );
	++it;
    }
    \endcode

    \sa filter() refresh()
*/

void TQDataTable::setSort( const TQStringList& sort )
{
    d->cur.setSort( sort );
}

/*!
    \overload

    Sets the sort to be applied to the displayed data to \a sort. If
    there is no current cursor, nothing happens. A TQSqlIndex tqcontains
    field names and their ordering (ASC or DESC); these are used to
    compose the ORDER BY clause.

    \sa sort()
*/

void TQDataTable::setSort( const TQSqlIndex& sort )
{
    d->cur.setSort( sort );
}

TQStringList TQDataTable::sort() const
{
    return d->cur.sort();
}

/*!
    Returns the cursor used by the data table.
*/

TQSqlCursor* TQDataTable::sqlCursor() const
{
    return d->cur.cursor();
}

void TQDataTable::setConfirmEdits( bool confirm )
{
    d->dat.setConfirmEdits( confirm );
}

void TQDataTable::setConfirmInsert( bool confirm )
{
    d->dat.setConfirmInsert( confirm );
}

void TQDataTable::setConfirmUpdate( bool confirm )
{
    d->dat.setConfirmUpdate( confirm );
}

void TQDataTable::setConfirmDelete( bool confirm )
{
    d->dat.setConfirmDelete( confirm );
}

/*!
    \property TQDataTable::confirmEdits
    \brief whether the data table confirms edit operations

    If the confirmEdits property is TRUE, the data table confirms all
    edit operations (inserts, updates and deletes). Finer control of
    edit confirmation can be achieved using \l confirmCancels, \l
    confirmInsert, \l confirmUpdate and \l confirmDelete.

    \sa confirmCancels() confirmInsert() confirmUpdate() confirmDelete()
*/

bool TQDataTable::confirmEdits() const
{
    return ( d->dat.confirmEdits() );
}

/*!
    \property TQDataTable::confirmInsert
    \brief whether the data table confirms insert operations

    If the confirmInsert property is TRUE, all insertions must be
    confirmed by the user through a message box (this behaviour can be
    changed by overriding the confirmEdit() function), otherwise all
    insert operations occur immediately.

    \sa confirmCancels() confirmEdits() confirmUpdate() confirmDelete()
*/

bool TQDataTable::confirmInsert() const
{
    return ( d->dat.confirmInsert() );
}

/*!
    \property TQDataTable::confirmUpdate
    \brief whether the data table confirms update operations

    If the confirmUpdate property is TRUE, all updates must be
    confirmed by the user through a message box (this behaviour can be
    changed by overriding the confirmEdit() function), otherwise all
    update operations occur immediately.

    \sa confirmCancels() confirmEdits() confirmInsert() confirmDelete()
*/

bool TQDataTable::confirmUpdate() const
{
    return ( d->dat.confirmUpdate() );
}

/*!
    \property TQDataTable::confirmDelete
    \brief whether the data table confirms delete operations

    If the confirmDelete property is TRUE, all deletions must be
    confirmed by the user through a message box (this behaviour can be
    changed by overriding the confirmEdit() function), otherwise all
    delete operations occur immediately.

    \sa confirmCancels() confirmEdits() confirmUpdate() confirmInsert()
*/

bool TQDataTable::confirmDelete() const
{
    return ( d->dat.confirmDelete() );
}

/*!
    \property TQDataTable::confirmCancels
    \brief whether the data table confirms cancel operations

    If the confirmCancel property is TRUE, all cancels must be
    confirmed by the user through a message box (this behavior can be
    changed by overriding the confirmCancel() function), otherwise all
    cancels occur immediately. The default is FALSE.

    \sa confirmEdits() confirmCancel()
*/

void TQDataTable::setConfirmCancels( bool confirm )
{
    d->dat.setConfirmCancels( confirm );
}

bool TQDataTable::confirmCancels() const
{
    return d->dat.confirmCancels();
}

/*!
    \reimp

    For an editable table, creates an editor suitable for the field in
    column \a col. The editor is created using the default editor
    factory, unless a different editor factory was installed with
    installEditorFactory(). The editor is primed with the value of the
    field in \a col using a property map. The property map used is the
    default property map, unless a new property map was installed with
    installPropertMap(). If \a initFromCell is TRUE then the editor is
    primed with the value in the TQDataTable cell.
*/

TQWidget * TQDataTable::createEditor( int , int col, bool initFromCell ) const
{
    if ( d->dat.mode() == TQSql::None )
	return 0;

    TQSqlEditorFactory * f = (d->editorFactory == 0) ?
		     TQSqlEditorFactory::defaultFactory() : d->editorFactory;

    TQSqlPropertyMap * m = (d->propertyMap == 0) ?
			  TQSqlPropertyMap::defaultMap() : d->propertyMap;

    TQWidget * w = 0;
    if( initFromCell && d->editBuffer ){
	w = f->createEditor( viewport(), d->editBuffer->field( indexOf( col ) ) );
	if ( w )
	    m->setProperty( w, d->editBuffer->value( indexOf( col ) ) );
    }
    return w;
}

/*! \reimp */
bool TQDataTable::eventFilter( TQObject *o, TQEvent *e )
{
    if ( d->cancelMode )
	return TRUE;

    int r = currentRow();
    int c = currentColumn();

    if ( d->dat.mode() != TQSql::None ) {
	r = d->editRow;
	c = d->editCol;
    }

    d->cancelInsert = FALSE;
    d->cancelUpdate = FALSE;
    switch ( e->type() ) {
    case TQEvent::KeyPress: {
	int conf = TQSql::Yes;
	TQKeyEvent *ke = (TQKeyEvent*)e;
	if ( ( ke->key() == Qt::Key_Tab || ke->key() == TQt::Key_BackTab )
	    && ke->state() & ControlButton )
	    return FALSE;

	if ( ke->key() == Key_Escape && d->dat.mode() == TQSql::Insert ){
	    if ( confirmCancels() && !d->cancelMode ) {
		d->cancelMode = TRUE;
		conf = confirmCancel( TQSql::Insert );
		d->cancelMode = FALSE;
	    }
	    if ( conf == TQSql::Yes ) {
		d->cancelInsert = TRUE;
	    } else {
		TQWidget *editorWidget = cellWidget( r, c );
		if ( editorWidget ) {
		    editorWidget->setActiveWindow();
		    editorWidget->setFocus();
		}
		return TRUE;
	    }
	}
	if ( ke->key() == Key_Escape && d->dat.mode() == TQSql::Update ) {
	    if ( confirmCancels() && !d->cancelMode ) {
		d->cancelMode = TRUE;
		conf = confirmCancel( TQSql::Update );
		d->cancelMode = FALSE;
	    }
	    if ( conf == TQSql::Yes ){
		d->cancelUpdate = TRUE;
	    } else {
		TQWidget *editorWidget = cellWidget( r, c );
		if ( editorWidget ) {
		    editorWidget->setActiveWindow();
		    editorWidget->setFocus();
		}
		return TRUE;
	    }
	}
	if ( ke->key() == Qt::Key_Insert && d->dat.mode() == TQSql::None ) {
	    beginInsert();
	    return TRUE;
	}
	if ( ke->key() == Qt::Key_Delete && d->dat.mode() == TQSql::None ) {
	    deleteCurrent();
	    return TRUE;
	}
	if ( d->dat.mode() != TQSql::None ) {
	    if ( (ke->key() == Qt::Key_Tab) && (c < numCols() - 1) && (!isColumnReadOnly( c+1 ) || d->dat.mode() == TQSql::Insert) )
		d->continuousEdit = TRUE;
	    else if ( (ke->key() == TQt::Key_BackTab) && (c > 0) && (!isColumnReadOnly( c-1 ) || d->dat.mode() == TQSql::Insert) )
		d->continuousEdit = TRUE;
	    else
		d->continuousEdit = FALSE;
	}
	TQSqlCursor * sql = sqlCursor();
	if ( sql && sql->driver() &&
	     !sql->driver()->hasFeature( TQSqlDriver::QuerySize ) &&
	     ke->key() == Qt::Key_End && d->dat.mode() == TQSql::None ) {
#ifndef TQT_NO_CURSOR
	    TQApplication::setOverrideCursor( TQt::WaitCursor );
#endif
	    int i = sql->at();
	    if ( i < 0 ) {
		i = 0;
		sql->seek(0);
	    }
	    while ( sql->next() )
		i++;
	    setNumRows( i+1 );
	    setCurrentCell( i+1, currentColumn() );
#ifndef TQT_NO_CURSOR
	    TQApplication::restoreOverrideCursor();
#endif
	    return TRUE;
	}
	break;
    }
    case TQEvent::FocusOut: {
	TQWidget *editorWidget = cellWidget( r, c );
	repaintCell( currentRow(), currentColumn() );
	if ( !d->cancelMode && editorWidget && TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(editorWidget) &&
	     ( d->dat.mode() == TQSql::Insert) && !d->continuousEdit) {
	    setCurrentCell( r, c );
	    d->cancelInsert = TRUE;
	}
	d->continuousEdit = FALSE;
	break;
    }
    case TQEvent::FocusIn:
	repaintCell( currentRow(), currentColumn() );
	break;
    default:
	break;
    }
    return TQTable::eventFilter( o, e );
}

/*! \reimp */
void TQDataTable::resizeEvent ( TQResizeEvent * e )
{
    if ( sqlCursor() &&
	 sqlCursor()->driver() &&
	 !sqlCursor()->driver()->hasFeature( TQSqlDriver::QuerySize ) )
	loadNextPage();
    TQTable::resizeEvent( e );
}

/*! \reimp */
void TQDataTable::contentsContextMenuEvent( TQContextMenuEvent* e )
{
    TQTable::contentsContextMenuEvent( e );
    if ( isEditing() && d->dat.mode() != TQSql::None )
	endEdit( d->editRow, d->editCol, autoEdit(), FALSE );
    if ( !sqlCursor() )
	return;
    if ( d->dat.mode() == TQSql::None ) {
	if ( isReadOnly() )
	    return;
	enum {
	    IdInsert,
	    IdUpdate,
	    IdDelete
	};
	TQGuardedPtr<TQPopupMenu> popup = new TQPopupMenu( this, "qt_datatable_menu" );
	int id[ 3 ];
	id[ IdInsert ] = popup->insertItem( tr( "Insert" ) );
	id[ IdUpdate ] = popup->insertItem( tr( "Update" ) );
	id[ IdDelete ] = popup->insertItem( tr( "Delete" ) );
	bool enableInsert = sqlCursor()->canInsert();
	popup->setItemEnabled( id[ IdInsert ], enableInsert );
	bool enableUpdate = currentRow() > -1 && sqlCursor()->canUpdate() && !isColumnReadOnly( currentColumn() );
	popup->setItemEnabled( id[ IdUpdate ], enableUpdate );
	bool enableDelete = currentRow() > -1 && sqlCursor()->canDelete();
	popup->setItemEnabled( id[ IdDelete ], enableDelete );
	int r = popup->exec( e->globalPos() );
	delete (TQPopupMenu*) popup;
	if ( r == id[ IdInsert ] )
	    beginInsert();
	else if ( r == id[ IdUpdate ] ) {
	    if ( beginEdit( currentRow(), currentColumn(), FALSE ) )
		setEditMode( Editing, currentRow(), currentColumn() );
	    else
		endUpdate();
	}
	else if ( r == id[ IdDelete ] )
	    deleteCurrent();
	e->accept();
    }
}

/*! \reimp */
void TQDataTable::contentsMousePressEvent( TQMouseEvent* e )
{
    TQTable::contentsMousePressEvent( e );
}

/*! \reimp */
TQWidget* TQDataTable::beginEdit ( int row, int col, bool tqreplace )
{
    d->editRow = -1;
    d->editCol = -1;
    if ( !sqlCursor() )
	return 0;
    if ( d->dat.mode() == TQSql::Insert && !sqlCursor()->canInsert() )
	return 0;
    if ( d->dat.mode() == TQSql::Update && !sqlCursor()->canUpdate() )
	return 0;
    d->editRow = row;
    d->editCol = col;
    if ( d->continuousEdit ) {
	// see comment in beginInsert()
	bool fakeReadOnly = isColumnReadOnly( col );
	setColumnReadOnly( col, FALSE );
	TQWidget* w = TQTable::beginEdit( row, col, tqreplace );
	setColumnReadOnly( col, fakeReadOnly );
	return w;
    }
    if ( d->dat.mode() == TQSql::None && sqlCursor()->canUpdate() && sqlCursor()->primaryIndex().count() > 0 )
	return beginUpdate( row, col, tqreplace );
    return 0;
}

/*! \reimp */
void TQDataTable::endEdit( int row, int col, bool, bool )
{
    bool accept = autoEdit() && !d->cancelInsert && !d->cancelUpdate;

    TQWidget *editor = cellWidget( row, col );
    if ( !editor )
	return;
    if ( d->cancelMode )
	return;
    if ( d->dat.mode() != TQSql::None && d->editBuffer ) {
	TQSqlPropertyMap * m = (d->propertyMap == 0) ?
			      TQSqlPropertyMap::defaultMap() : d->propertyMap;
	d->editBuffer->setValue( indexOf( col ),  m->property( editor ) );
	clearCellWidget( row, col );
	if ( !d->continuousEdit ) {
	    switch ( d->dat.mode() ) {
	    case TQSql::Insert:
		if ( accept )
		    TQTimer::singleShot( 0, this, TQT_SLOT( doInsertCurrent() ) );
		else
		    endInsert();
		break;
	    case TQSql::Update:
		if ( accept )
		    TQTimer::singleShot( 0, this, TQT_SLOT( doUpdateCurrent() ) );
		else
		    endUpdate();
		break;
	    default:
		break;
	    }
	}
    } else {
	setEditMode( NotEditing, -1, -1 );
    }
    if ( d->dat.mode() == TQSql::None )
	viewport()->setFocus();
    updateCell( row, col );
    emit valueChanged( row, col );
}

/*! \internal */
void TQDataTable::doInsertCurrent()
{
    insertCurrent();
}

/*! \internal */
void TQDataTable::doUpdateCurrent()
{
    updateCurrent();
    if ( d->dat.mode() == TQSql::None ) {
	viewport()->setFocus();
    }
}

/*! \reimp */
void TQDataTable::activateNextCell()
{
//     if ( d->dat.mode() == TQSql::None )
//	TQTable::activateNextCell();
}

/*! \internal
*/

void TQDataTable::endInsert()
{
    if ( d->dat.mode() != TQSql::Insert )
	return;
    d->dat.setMode( TQSql::None );
    d->editBuffer = 0;
    verticalHeader()->setLabel( d->editRow, TQString::number( d->editRow +1 ) );
    d->editRow = -1;
    d->editCol = -1;
    d->insertRowLast = -1;
    d->insertHeaderLabelLast = TQString::null;
    setEditMode( NotEditing, -1, -1 );
    setNumRows( d->insertPreRows );
    d->insertPreRows = -1;
    viewport()->setFocus();
}

/*! \internal
*/

void TQDataTable::endUpdate()
{
    d->dat.setMode( TQSql::None );
    d->editBuffer = 0;
    updateRow( d->editRow );
    d->editRow = -1;
    d->editCol = -1;
    setEditMode( NotEditing, -1, -1 );
}

/*!
    Protected virtual function called when editing is about to begin
    on a new record. If the table is read-only, or if there's no
    cursor or the cursor does not allow inserts, nothing happens.

    Editing takes place using the cursor's edit buffer(see
    TQSqlCursor::editBuffer()).

    When editing begins, a new row is created in the table marked with
    an asterisk '*' in the row's vertical header column, i.e. at the
    left of the row.
*/

bool TQDataTable::beginInsert()
{
    if ( !sqlCursor() || isReadOnly() || !numCols() )
	return FALSE;
    if ( !sqlCursor()->canInsert() )
	return FALSE;
    int i = 0;
    int row = currentRow();

    d->insertPreRows = numRows();
    if ( row < 0 || numRows() < 1 )
	row = 0;
    setNumRows( d->insertPreRows + 1 );
    setCurrentCell( row, 0 );
    d->editBuffer = sqlCursor()->primeInsert();
    emit primeInsert( d->editBuffer );
    d->dat.setMode( TQSql::Insert );
    int lastRow = row;
    int lastY = contentsY() + visibleHeight();
    for ( i = row; i < numRows() ; ++i ) {
	TQRect cg = cellGeometry( i, 0 );
	if ( (cg.y()+cg.height()) > lastY ) {
	    lastRow = i;
	    break;
	}
    }
    if ( lastRow == row && ( numRows()-1 > row ) )
	lastRow = numRows() - 1;
    d->insertRowLast = lastRow;
    d->insertHeaderLabelLast = verticalHeader()->label( d->insertRowLast );
    verticalHeader()->setLabel( row, "*" );
    d->editRow = row;
    // in the db world it's common to allow inserting new records
    // into a table that has read-only columns - temporarily
    // switch off read-only mode for such columns
    bool fakeReadOnly = isColumnReadOnly( 0 );
    setColumnReadOnly( 0, FALSE );
    if ( TQTable::beginEdit( row, 0, FALSE ) )
	setEditMode( Editing, row, 0 );
    setColumnReadOnly( 0, fakeReadOnly );
    return TRUE;
}

/*!
    Protected virtual function called when editing is about to begin
    on an existing row. If the table is read-only, or if there's no
    cursor, nothing happens.

    Editing takes place using the cursor's edit buffer (see
    TQSqlCursor::editBuffer()).

    \a row and \a col refer to the row and column in the TQDataTable.

    (\a tqreplace is provided for reimplementors and reflects the API of
    TQTable::beginEdit().)
*/

TQWidget* TQDataTable::beginUpdate ( int row, int col, bool tqreplace )
{
    if ( !sqlCursor() || isReadOnly() || isColumnReadOnly( col ) )
	return 0;
    setCurrentCell( row, col );
    d->dat.setMode( TQSql::Update );
    if ( sqlCursor()->seek( row ) ) {
	d->editBuffer = sqlCursor()->primeUpdate();
	sqlCursor()->seek( currentRow() );
	emit primeUpdate( d->editBuffer );
	return TQTable::beginEdit( row, col, tqreplace );
    }
    return 0;
}

/*!
    For an editable table, issues an insert on the current cursor
    using the values in the cursor's edit buffer. If there is no
    current cursor or there is no current "insert" row, nothing
    happens. If confirmEdits() or confirmInsert() is TRUE,
    confirmEdit() is called to confirm the insert. Returns TRUE if the
    insert succeeded; otherwise returns FALSE.

    The underlying cursor must have a valid primary index to ensure
    that a unique record is inserted within the database otherwise the
    database may be changed to an inconsistent state.
*/

bool TQDataTable::insertCurrent()
{
    if ( d->dat.mode() != TQSql::Insert || ! numCols() )
	return FALSE;
    if ( !sqlCursor()->canInsert() ) {
#ifdef TQT_CHECK_RANGE
	qWarning("TQDataTable::insertCurrent: insert not allowed for %s",
		 sqlCursor()->name().latin1() );
#endif
	endInsert();
	return FALSE;
    }
    int b = 0;
    int conf = TQSql::Yes;
    if ( confirmEdits() || confirmInsert() )
	conf = confirmEdit( TQSql::Insert );
    switch ( conf ) {
    case TQSql::Yes: {
#ifndef TQT_NO_CURSOR
	TQApplication::setOverrideCursor( Qt::WaitCursor );
#endif
	emit beforeInsert( d->editBuffer );
	b = sqlCursor()->insert();
#ifndef TQT_NO_CURSOR
	TQApplication::restoreOverrideCursor();
#endif
	if ( ( !b && !sqlCursor()->isActive() ) || !sqlCursor()->isActive() ) {
	    handleError( sqlCursor()->lastError() );
	    endInsert(); // cancel the insert if anything goes wrong
	    refresh();
	} else {
	    endInsert();
	    refresh();
	    TQSqlIndex idx = sqlCursor()->primaryIndex();
	    tqfindBuffer( idx, d->lastAt );
	    repaintContents( contentsX(), contentsY(), visibleWidth(), visibleHeight(), FALSE );
	    emit cursorChanged( TQSql::Insert );
	}
	break;
    }
    case TQSql::No:
	endInsert();
	break;
    case TQSql::Cancel:
	if ( TQTable::beginEdit( currentRow(), currentColumn(), FALSE ) )
	    setEditMode( Editing, currentRow(), currentColumn() );
	break;
    }
    return ( b > 0 );
}

/*! \internal

  Updates the row \a row.
*/

void TQDataTable::updateRow( int row )
{
    for ( int i = 0; i < numCols(); ++i )
	updateCell( row, i );
}

/*!
    For an editable table, issues an update using the cursor's edit
    buffer. If there is no current cursor or there is no current
    selection, nothing happens. If confirmEdits() or confirmUpdate()
    is TRUE, confirmEdit() is called to confirm the update. Returns
    TRUE if the update succeeded; otherwise returns FALSE.

    The underlying cursor must have a valid primary index to ensure
    that a unique record is updated within the database otherwise the
    database may be changed to an inconsistent state.
*/

bool TQDataTable::updateCurrent()
{
    if ( d->dat.mode() != TQSql::Update )
	return FALSE;
    if ( sqlCursor()->primaryIndex().count() == 0 ) {
#ifdef TQT_CHECK_RANGE
	qWarning("TQDataTable::updateCurrent: no primary index for %s",
		 sqlCursor()->name().latin1() );
#endif
	endUpdate();
	return FALSE;
    }
    if ( !sqlCursor()->canUpdate() ) {
#ifdef TQT_CHECK_RANGE
	qWarning("TQDataTable::updateCurrent: updates not allowed for %s",
		 sqlCursor()->name().latin1() );
#endif
	endUpdate();
	return FALSE;
    }
    int b = 0;
    int conf = TQSql::Yes;
    if ( confirmEdits() || confirmUpdate() )
	conf = confirmEdit( TQSql::Update );
    switch ( conf ) {
    case TQSql::Yes: {
#ifndef TQT_NO_CURSOR
	TQApplication::setOverrideCursor( Qt::WaitCursor );
#endif
	emit beforeUpdate( d->editBuffer );
	b = sqlCursor()->update();
#ifndef TQT_NO_CURSOR
	TQApplication::restoreOverrideCursor();
#endif
	if ( ( !b && !sqlCursor()->isActive() ) || !sqlCursor()->isActive() ) {
	    handleError( sqlCursor()->lastError() );
	    endUpdate();
	    refresh();
	    setCurrentCell( d->editRow, d->editCol );
	    if ( TQTable::beginEdit( d->editRow, d->editCol, FALSE ) )
		setEditMode( Editing, d->editRow, d->editCol );
	} else {
	    emit cursorChanged( TQSql::Update );
	    refresh();
	    endUpdate();
	}
	break;
    }
    case TQSql::No:
	endUpdate();
	setEditMode( NotEditing, -1, -1 );
	break;
    case TQSql::Cancel:
	setCurrentCell( d->editRow, d->editCol );
	if ( TQTable::beginEdit( d->editRow, d->editCol, FALSE ) )
	    setEditMode( Editing, d->editRow, d->editCol );
	break;
    }
    return ( b > 0 );
}

/*!
    For an editable table, issues a delete on the current cursor's
    primary index using the values of the currently selected row. If
    there is no current cursor or there is no current selection,
    nothing happens. If confirmEdits() or confirmDelete() is TRUE,
    confirmEdit() is called to confirm the delete. Returns TRUE if the
    delete succeeded; otherwise FALSE.

    The underlying cursor must have a valid primary index to ensure
    that a unique record is deleted within the database otherwise the
    database may be changed to an inconsistent state.
*/

bool TQDataTable::deleteCurrent()
{
    if ( !sqlCursor() || isReadOnly() )
	return FALSE;
    if ( sqlCursor()->primaryIndex().count() == 0 ) {
#ifdef TQT_CHECK_RANGE
	qWarning("TQDataTable::deleteCurrent: no primary index %s",
		 sqlCursor()->name().latin1() );
#endif
	return FALSE;
    }
    if ( !sqlCursor()->canDelete() )
	return FALSE;

    int b = 0;
    int conf = TQSql::Yes;
    if ( confirmEdits() || confirmDelete() )
	conf = confirmEdit( TQSql::Delete );

    // Have to have this here - the confirmEdit() might pop up a
    // dialog that causes a tqrepaint which the cursor to the
    // record it has to tqrepaint.
    if ( !sqlCursor()->seek( currentRow() ) )
	return FALSE;
    switch ( conf ) {
	case TQSql::Yes:{
#ifndef TQT_NO_CURSOR
	    TQApplication::setOverrideCursor( Qt::WaitCursor );
#endif
	    sqlCursor()->primeDelete();
	    emit primeDelete( sqlCursor()->editBuffer() );
	    emit beforeDelete( sqlCursor()->editBuffer() );
	    b = sqlCursor()->del();
#ifndef TQT_NO_CURSOR
	    TQApplication::restoreOverrideCursor();
#endif
	    if ( !b )
		handleError( sqlCursor()->lastError() );
	    refresh();
	    emit cursorChanged( TQSql::Delete );
	    setCurrentCell( currentRow(), currentColumn() );
	    repaintContents( contentsX(), contentsY(), visibleWidth(), visibleHeight(), FALSE );
	    verticalHeader()->tqrepaint(); // get rid of trailing garbage
	}
	break;
    case TQSql::No:
	setEditMode( NotEditing, -1, -1 );
	break;
    }
    return ( b > 0 );
}

/*!
    Protected virtual function which returns a confirmation for an
    edit of mode \a m. Derived classes can reimplement this function
    to provide their own confirmation dialog. The default
    implementation uses a message box which prompts the user to
    confirm the edit action.
*/

TQSql::Confirm TQDataTable::confirmEdit( TQSql::Op m )
{
    return d->dat.confirmEdit( this, m );
}

/*!
    Protected virtual function which returns a confirmation for
    cancelling an edit mode of \a m. Derived classes can reimplement
    this function to provide their own cancel dialog. The default
    implementation uses a message box which prompts the user to
    confirm the cancel.
*/

TQSql::Confirm  TQDataTable::confirmCancel( TQSql::Op m )
{
    return d->dat.confirmCancel( this, m );
}


/*!
    Searches the current cursor for a cell containing the string \a
    str starting at the current cell and working forwards (or
    backwards if \a backwards is TRUE). If the string is found, the
    cell containing the string is set as the current cell. If \a
    caseSensitive is FALSE the case of \a str will be ignored.

    The search will wrap, i.e. if the first (or if backwards is TRUE,
    last) cell is reached without tqfinding \a str the search will
    continue until it reaches the starting cell. If \a str is not
    found the search will fail and the current cell will remain
    unchanged.
*/
void TQDataTable::tqfind( const TQString & str, bool caseSensitive, bool backwards )
{
    if ( !sqlCursor() )
	return;

    TQSqlCursor * r = sqlCursor();
    TQString tmp, text;
    uint  row = currentRow(), startRow = row,
	  col = backwards ? currentColumn() - 1 : currentColumn() + 1;
    bool  wrap = TRUE, found = FALSE;

    if( str.isEmpty() || str.isNull() )
	return;

    if( !caseSensitive )
	tmp = str.lower();
    else
	tmp = str;

#ifndef TQT_NO_CURSOR
    TQApplication::setOverrideCursor( Qt::WaitCursor );
#endif
    while( wrap ){
	while( !found && r->seek( row ) ){
	    for( int i = col; backwards ? (i >= 0) : (i < (int) numCols());
		 backwards ? i-- : i++ )
	    {
		text = r->value( indexOf( i ) ).toString();
		if( !caseSensitive ){
		    text = text.lower();
		}
		if( text.tqcontains( tmp ) ){
		    setCurrentCell( row, i );
		    col = i;
		    found = TRUE;
		}
	    }
	    if( !backwards ){
		col = 0;
		row++;
	    } else {
		col = numCols() - 1;
		row--;
	    }
	}
	if( !backwards ){
	    if( startRow != 0 ){
		startRow = 0;
	    } else {
		wrap = FALSE;
	    }
	    r->first();
	    row = 0;
	} else {
	    if( startRow != (uint) (numRows() - 1) ){
		startRow = numRows() - 1;
	    } else {
		wrap = FALSE;
	    }
	    r->last();
	    row = numRows() - 1;
	}
    }
#ifndef TQT_NO_CURSOR
    TQApplication::restoreOverrideCursor();
#endif
}


/*!
    Resets the table so that it displays no data.

    \sa setSqlCursor()
*/

void TQDataTable::reset()
{
    clearCellWidget( currentRow(), currentColumn() );
    switch ( d->dat.mode() ) {
    case TQSql::Insert:
	endInsert();
	break;
    case TQSql::Update:
	endUpdate();
	break;
    default:
	break;
    }
    ensureVisible( 0, 0 );
    verticalScrollBar()->setValue(0);
    setNumRows(0);

    d->haveAllRows = FALSE;
    d->continuousEdit = FALSE;
    d->dat.setMode( TQSql::None );
    d->editRow = -1;
    d->editCol = -1;
    d->insertRowLast = -1;
    d->insertHeaderLabelLast = TQString::null;
    d->cancelMode = FALSE;
    d->lastAt = -1;
    d->fld.clear();
    d->fldLabel.clear();
    d->fldWidth.clear();
    d->fldIcon.clear();
    d->fldHidden.clear();
    if ( sorting() )
	horizontalHeader()->setSortIndicator( -1 );
}

/*!
    Returns the index of the field within the current SQL query that
    is displayed in column \a i.
*/

int TQDataTable::indexOf( uint i ) const
{
    TQDataTablePrivate::ColIndex::ConstIterator it = d->colIndex.at( i );
    if ( it != d->colIndex.end() )
	return *it;
    return -1;
}

/*!
    Returns TRUE if the table will automatically delete the cursor
    specified by setSqlCursor(); otherwise returns FALSE.
*/

bool TQDataTable::autoDelete() const
{
    return d->cur.autoDelete();
}

/*!
    Sets the cursor auto-delete flag to \a enable. If \a enable is
    TRUE, the table will automatically delete the cursor specified by
    setSqlCursor(). If \a enable is FALSE (the default), the cursor
    will not be deleted.
*/

void TQDataTable::setAutoDelete( bool enable )
{
    d->cur.setAutoDelete( enable );
}

/*!
    \property TQDataTable::autoEdit
    \brief whether the data table automatically applies edits

    The default value for this property is TRUE. When the user begins
    an insert or update in the table there are two possible outcomes
    when they navigate to another record:

    \list 1
    \i the insert or update is is performed -- this occurs if autoEdit is TRUE
    \i the insert or update is abandoned -- this occurs if autoEdit is FALSE
    \endlist
*/

void TQDataTable::setAutoEdit( bool autoEdit )
{
    d->dat.setAutoEdit( autoEdit );
}

bool TQDataTable::autoEdit() const
{
    return d->dat.autoEdit();
}

/*!
    \property TQDataTable::nullText
    \brief the text used to represent NULL values

    The nullText property will be used to represent NULL values in the
    table. The default value is provided by the cursor's driver.
*/

void TQDataTable::setNullText( const TQString& nullText )
{
    d->nullTxt = nullText;
    d->nullTxtChanged = TRUE;
}

TQString TQDataTable::nullText() const
{
    return d->nullTxt;
}

/*!
    \property TQDataTable::trueText
    \brief the text used to represent true values

    The trueText property will be used to represent NULL values in the
    table. The default value is "True".
*/

void TQDataTable::setTrueText( const TQString& trueText )
{
    d->trueTxt = trueText;
}

TQString TQDataTable::trueText() const
{
    return d->trueTxt;
}

/*!
    \property TQDataTable::falseText
    \brief the text used to represent false values

    The falseText property will be used to represent NULL values in
    the table. The default value is "False".
*/

void TQDataTable::setFalseText( const TQString& falseText )
{
    d->falseTxt = falseText;
}

TQString TQDataTable::falseText() const
{
    return d->falseTxt;
}

/*!
    \property TQDataTable::dateFormat
    \brief the format used for displaying date/time values

    The dateFormat property is used for displaying date/time values in
    the table. The default value is \c TQt::LocalDate.
*/

void TQDataTable::setDateFormat( const Qt::DateFormat f )
{
    d->datefmt = f;
}

Qt::DateFormat TQDataTable::dateFormat() const
{
    return d->datefmt;
}

/*!
    \property TQDataTable::numRows

    \brief the number of rows in the table
*/

int TQDataTable::numRows() const
{
    return TQTable::numRows();
}

/*!
    \reimp

    The number of rows in the table will be determined by the cursor
    (see setSqlCursor()), so normally this function should never be
    called. It is included for completeness.
*/

void TQDataTable::setNumRows ( int r )
{
    TQTable::setNumRows( r );
}

/*!
    \reimp

    The number of columns in the table will be determined
    automatically (see addColumn()), so normally this function should
    never be called. It is included for completeness.
*/

void TQDataTable::setNumCols ( int r )
{
    TQTable::setNumCols( r );
}

/*!
    \property TQDataTable::numCols

    \brief the number of columns in the table
*/

int TQDataTable::numCols() const
{
    return TQTable::numCols();
}

/*!
    Returns the text in cell \a row, \a col, or an empty string if the
    cell is empty. If the cell's value is NULL then nullText() will be
    returned. If the cell does not exist then TQString::null is
    returned.
*/

TQString TQDataTable::text ( int row, int col ) const
{
    if ( !sqlCursor() )
	return TQString::null;

    TQString s;
    if ( sqlCursor()->seek( row ) )
	s = sqlCursor()->value( indexOf( col ) ).toString();
    sqlCursor()->seek( currentRow() );
    return s;
}

/*!
    Returns the value in cell \a row, \a col, or an invalid value if
    the cell does not exist or has no value.
*/

TQVariant TQDataTable::value ( int row, int col ) const
{
    if ( !sqlCursor() )
	return TQVariant();

    TQVariant v;
    if ( sqlCursor()->seek( row ) )
	v = sqlCursor()->value( indexOf( col ) );
    sqlCursor()->seek( currentRow() );
    return v;
}

/*!  \internal
  Used to update the table when the size of the result set cannot be
  determined - divide the result set into pages and load the pages as
  the user moves around in the table.
*/
void TQDataTable::loadNextPage()
{
    if ( d->haveAllRows )
	return;
    if ( !sqlCursor() )
	return;
    int pageSize = 0;
    int lookAhead = 0;
    if ( height() ) {
	pageSize = (int)( height() * 2 / 20 );
	lookAhead = pageSize / 2;
    }
    int startIdx = verticalScrollBar()->value() / 20;
    int endIdx = startIdx + pageSize + lookAhead;
    if ( endIdx < numRows() || endIdx < 0 )
	return;

    // check for empty result set
    if ( sqlCursor()->at() == TQSql::BeforeFirst && !sqlCursor()->next() ) {
	d->haveAllRows = TRUE;
	return;
    }

    while ( endIdx > 0 && !sqlCursor()->seek( endIdx ) )
	endIdx--;
    if ( endIdx != ( startIdx + pageSize + lookAhead ) )
	d->haveAllRows = TRUE;
    // small hack to prevent TQTable from moving the view when a row
    // is selected and the contents is resized
    SelectionMode m = selectionMode();
    clearSelection();
    setSelectionMode( NoSelection );
    setNumRows( endIdx + 1 );
    sqlCursor()->seek( currentRow() );
    setSelectionMode( m );
}

/*! \internal */
void TQDataTable::sliderPressed()
{
    disconnect( verticalScrollBar(), TQT_SIGNAL( valueChanged(int) ),
		this, TQT_SLOT( loadNextPage() ) );
}

/*! \internal */
void TQDataTable::sliderReleased()
{
    loadNextPage();
    connect( verticalScrollBar(), TQT_SIGNAL( valueChanged(int) ),
	     this, TQT_SLOT( loadNextPage() ) );
}

/*!
    Sorts column \a col in ascending order if \a ascending is TRUE
    (the default); otherwise sorts in descending order.

    The \a wholeRows parameter is ignored; TQDataTable always sorts
    whole rows by the specified column.
*/

void TQDataTable::sortColumn ( int col, bool ascending,
			      bool  )
{
    if ( sorting() ) {
	if ( isEditing() && d->dat.mode() != TQSql::None )
	    endEdit( d->editRow, d->editCol, autoEdit(), FALSE );
	if ( !sqlCursor() )
	    return;
	TQSqlIndex lastSort = sqlCursor()->sort();
	TQSqlIndex newSort( lastSort.cursorName(), "newSort" );
	TQSqlField *field = sqlCursor()->field( indexOf( col ) );
	if ( field )
	    newSort.append( *field );
	newSort.setDescending( 0, !ascending );
	horizontalHeader()->setSortIndicator( col, ascending );
	setSort( newSort );
	refresh();
    }
}

/*! \reimp */
void TQDataTable::columnClicked ( int col )
{
    if ( sorting() ) {
	if ( !sqlCursor() )
	    return;
	TQSqlIndex lastSort = sqlCursor()->sort();
	bool asc = TRUE;
	if ( lastSort.count() && lastSort.field( 0 )->name() == sqlCursor()->field( indexOf( col ) )->name() )
	    asc = lastSort.isDescending( 0 );
	sortColumn( col, asc );
	emit currentChanged( sqlCursor() );
    }
}

/*!
    \reimp

    Repaints the cell at \a row, \a col.
*/
void TQDataTable::repaintCell( int row, int col )
{
    TQRect cg = cellGeometry( row, col );
    TQRect re( TQPoint( cg.x() - 2, cg.y() - 2 ),
	      TQSize( cg.width() + 4, cg.height() + 4 ) );
    repaintContents( re, FALSE );
}

/*!
    \reimp

    This function renders the cell at \a row, \a col with the value of
    the corresponding cursor field on the painter \a p. Depending on
    the table's current edit mode, paintField() is called for the
    appropriate cursor field. \a cr describes the cell coordinates in
    the content coordinate system. If \a selected is TRUE the cell has
    been selected and would normally be rendered differently than an
    unselected cell.

    \sa TQSql::isNull()
*/

void TQDataTable::paintCell( TQPainter * p, int row, int col, const TQRect & cr,
			  bool selected, const TQColorGroup &cg )
{
    TQTable::paintCell( p, row, col, cr, selected, cg );  // empty cell

    if ( !sqlCursor() )
	return;

    p->setPen( selected ? cg.highlightedText() : cg.text() );
    if ( d->dat.mode() != TQSql::None ) {
	if ( row == d->editRow && d->editBuffer ) {
	    paintField( p, d->editBuffer->field( indexOf( col ) ), cr,
			selected );
	} else if ( row > d->editRow && d->dat.mode() == TQSql::Insert ) {
	    if ( sqlCursor()->seek( row - 1 ) )
		paintField( p, sqlCursor()->field( indexOf( col ) ), cr,
			    selected );
	} else {
	    if ( sqlCursor()->seek( row ) )
		paintField( p, sqlCursor()->field( indexOf( col ) ), cr,
			    selected );
	}
    } else {
	if ( sqlCursor()->seek( row ) )
		paintField( p, sqlCursor()->field( indexOf( col ) ), cr, selected );

    }
}


/*!
    Paints the \a field on the painter \a p. The painter has already
    been translated to the appropriate cell's origin where the \a
    field is to be rendered. \a cr describes the cell coordinates in
    the content coordinate system. The \a selected parameter is
    ignored.

    If you want to draw custom field content you must reimplement
    paintField() to do the custom drawing. The default implementation
    renders the \a field value as text. If the field is NULL,
    nullText() is displayed in the cell. If the field is Boolean,
    trueText() or falseText() is displayed as appropriate.
*/

void TQDataTable::paintField( TQPainter * p, const TQSqlField* field,
			    const TQRect & cr, bool )
{
    if ( !field )
	return;
    p->drawText( 2,2, cr.width()-4, cr.height()-4, fieldAlignment( field ), fieldToString( field ) );
}

/*!
    Returns the tqalignment for \a field.
*/

int TQDataTable::fieldAlignment( const TQSqlField* /*field*/ )
{
    return TQt::AlignLeft | TQt::AlignVCenter; //## Reggie: add tqalignment to TQTable
}


/*!
    If the cursor's \a sql driver supports query sizes, the number of
    rows in the table is set to the size of the query. Otherwise, the
    table dynamically resizes itself as it is scrolled. If \a sql is
    not active, it is made active by issuing a select() on the cursor
    using the \a sql cursor's current filter and current sort.
*/

void TQDataTable::setSize( TQSqlCursor* sql )
{
    // ### what are the connect/disconnect calls doing here!? move to refresh()
    if ( sql->driver() && sql->driver()->hasFeature( TQSqlDriver::QuerySize ) ) {
	setVScrollBarMode( Auto );
 	disconnect( verticalScrollBar(), TQT_SIGNAL( sliderPressed() ),
		    this, TQT_SLOT( sliderPressed() ) );
 	disconnect( verticalScrollBar(), TQT_SIGNAL( sliderReleased() ),
		    this, TQT_SLOT( sliderReleased() ) );
	disconnect( verticalScrollBar(), TQT_SIGNAL( valueChanged(int) ),
		    this, TQT_SLOT( loadNextPage() ) );
	if ( numRows() != sql->size() )
	    setNumRows( sql->size() );
    } else {
	setVScrollBarMode( AlwaysOn );
 	connect( verticalScrollBar(), TQT_SIGNAL( sliderPressed() ),
 		 this, TQT_SLOT( sliderPressed() ) );
 	connect( verticalScrollBar(), TQT_SIGNAL( sliderReleased() ),
 		 this, TQT_SLOT( sliderReleased() ) );
	connect( verticalScrollBar(), TQT_SIGNAL( valueChanged(int) ),
		 this, TQT_SLOT( loadNextPage() ) );
	setNumRows(0);
	loadNextPage();
    }
}

/*!
    Sets \a cursor as the data source for the table. To force the
    display of the data from \a cursor, use refresh(). If \a
    autoPopulate is TRUE, columns are automatically created based upon
    the fields in the \a cursor record. If \a autoDelete is TRUE (the
    default is FALSE), the table will take ownership of the \a cursor
    and delete it when appropriate. If the \a cursor is read-only, the
    table becomes read-only. The table adopts the cursor's driver's
    definition for representing NULL values as strings.

    \sa refresh() setReadOnly() setAutoDelete() TQSqlDriver::nullText()
*/

void TQDataTable::setSqlCursor( TQSqlCursor* cursor, bool autoPopulate, bool autoDelete )
{
    setUpdatesEnabled( FALSE );
    d->cur.setCursor( 0 );
    if ( cursor ) {
	d->cur.setCursor( cursor, autoDelete );
	if ( autoPopulate ) {
	    d->fld.clear();
	    d->fldLabel.clear();
	    d->fldWidth.clear();
	    d->fldIcon.clear();
	    d->fldHidden.clear();
	    for ( uint i = 0; i < sqlCursor()->count(); ++i ) {
		addColumn( sqlCursor()->field( i )->name(), sqlCursor()->field( i )->name() );
		setColumnReadOnly( i, sqlCursor()->field( i )->isReadOnly() );
	    }
	}
	setReadOnly( sqlCursor()->isReadOnly() );
	if ( sqlCursor()->driver() && !d->nullTxtChanged )
	    setNullText(sqlCursor()->driver()->nullText() );
	setAutoDelete( autoDelete );
    } else {
	setNumRows( 0 );
	setNumCols( 0 );
    }
    setUpdatesEnabled( TRUE );
}


/*!
    Protected virtual function which is called when an error \a e has
    occurred on the current cursor(). The default implementation
    displays a warning message to the user with information about the
    error.
*/
void TQDataTable::handleError( const TQSqlError& e )
{
    d->dat.handleError( this, e );
}

/*! \reimp
  */

void TQDataTable::keyPressEvent( TQKeyEvent* e )
{
    switch( e->key() ) {
    case Qt::Key_Left:
    case Qt::Key_Right:
    case Qt::Key_Up:
    case Qt::Key_Down:
    case TQt::Key_Prior:
    case TQt::Key_Next:
    case Qt::Key_Home:
    case Qt::Key_End:
    case Qt::Key_F2:
    case Qt::Key_Enter: case Qt::Key_Return:
    case Qt::Key_Tab: case TQt::Key_BackTab:
	TQTable::keyPressEvent( e );
    default:
	return;
    }
}

/*!  \reimp
*/

void TQDataTable::resizeData ( int )
{

}

/*!  \reimp
*/

TQTableItem * TQDataTable::item ( int, int ) const
{
    return 0;
}

/*!  \reimp
*/

void TQDataTable::setItem ( int , int , TQTableItem * )
{

}

/*!  \reimp
*/

void TQDataTable::clearCell ( int , int )
{

}

/*!  \reimp
*/

void TQDataTable::setPixmap ( int , int , const TQPixmap &  )
{

}

/*! \reimp */
void TQDataTable::takeItem ( TQTableItem * )
{

}

/*!
    Installs a new SQL editor factory \a f. This enables the user to
    create and instantiate their own editors for use in cell editing.
    Note that TQDataTable takes ownership of this pointer, and will
    delete it when it is no longer needed or when
    installEditorFactory() is called again.

    \sa TQSqlEditorFactory
*/

void TQDataTable::installEditorFactory( TQSqlEditorFactory * f )
{
    if( f ) {
	delete d->editorFactory;
	d->editorFactory = f;
    }
}

/*!
    Installs a new property map \a m. This enables the user to create
    and instantiate their own property maps for use in cell editing.
    Note that TQDataTable takes ownership of this pointer, and will
    delete it when it is no longer needed or when installPropertMap()
    is called again.

    \sa TQSqlPropertyMap
*/

void TQDataTable::installPropertyMap( TQSqlPropertyMap* m )
{
    if ( m ) {
	delete d->propertyMap;
	d->propertyMap = m;
    }
}

/*!  \internal

  Sets the current selection to \a row, \a col.
*/

void TQDataTable::setCurrentSelection( int row, int )
{
    if ( !sqlCursor() )
	return;
    if ( row == d->lastAt )
	return;
    if ( !sqlCursor()->seek( row ) )
	return;
    d->lastAt = row;
    emit currentChanged( sqlCursor() );
}

void TQDataTable::updateCurrentSelection()
{
    setCurrentSelection( currentRow(), -1 );
}

/*!
    Returns the currently selected record, or 0 if there is no current
    selection. The table owns the pointer, so do \e not delete it or
    otherwise modify it or the cursor it points to.
*/

TQSqlRecord* TQDataTable::currentRecord() const
{
    if ( !sqlCursor() || currentRow() < 0 )
	return 0;
    if ( !sqlCursor()->seek( currentRow() ) )
	return 0;
    return sqlCursor();
}

/*!
    Sorts column \a col in ascending order.

    \sa setSorting()
*/

void TQDataTable::sortAscending( int col )
{
    sortColumn( col, TRUE );
}

/*!
    Sorts column \a col in descending order.

    \sa setSorting()
*/

void TQDataTable::sortDescending( int col )
{
    sortColumn( col, FALSE );
}

/*!
    \overload void TQDataTable::refresh( Refresh mode )

    Refreshes the table. If there is no currently defined cursor (see
    setSqlCursor()), nothing happens. The \a mode parameter determines
    which type of refresh will take place.

    \sa Refresh setSqlCursor() addColumn()
*/

void TQDataTable::refresh( TQDataTable::Refresh mode )
{
    TQSqlCursor* cur = sqlCursor();
    if ( !cur )
	return;
    bool refreshData = ( (mode & RefreshData) == RefreshData );
    bool refreshCol = ( (mode & RefreshColumns) == RefreshColumns );
    if ( ( (mode & RefreshAll) == RefreshAll ) ) {
	refreshData = TRUE;
	refreshCol = TRUE;
    }
    if ( !refreshCol && d->fld.count() && numCols() == 0 )
	refreshCol = TRUE;
    viewport()->setUpdatesEnabled( FALSE );
    d->haveAllRows = FALSE;
    if ( refreshData ) {
	if ( !d->cur.refresh() && d->cur.cursor() ) {
	    handleError( d->cur.cursor()->lastError() );
	}
	d->lastAt = -1;
    }
    if ( refreshCol ) {
	setNumCols( 0 );
	d->colIndex.clear();
	if ( d->fld.count() ) {
	    TQSqlField* field = 0;
	    int i;
	    int fpos = -1;
	    for ( i = 0; i < (int)d->fld.count(); ++i ) {
		if ( cur->field( i ) && cur->field( i )->name() == d->fld[ i ] )
		    // if there is a field with the desired name on the desired position
		    // then we take that
		    fpos = i;
		else
		    // otherwise we take the first field that matches the desired name
		    fpos = cur->position( d->fld[ i ] );
		field = cur->field( fpos );
		if ( field && ( cur->isGenerated( fpos ) ||
				cur->isCalculated( field->name() ) ) )
		{
		    setNumCols( numCols() + 1 );
		    d->colIndex.append( fpos );
		    setColumnReadOnly( numCols()-1, field->isReadOnly() || isColumnReadOnly( numCols()-1 ) );
		    horizontalHeader()->setLabel( numCols()-1, d->fldIcon[ i ], d->fldLabel[ i ] );
		    if ( d->fldHidden[ i ] ) {
			TQTable::showColumn( i ); // ugly but necessary
			TQTable::hideColumn( i );
		    } else {
			TQTable::showColumn( i );
		    }
		    if ( d->fldWidth[ i ] > -1 )
			TQTable::setColumnWidth( i, d->fldWidth[i] );
		}
	    }
	}
    }
    viewport()->setUpdatesEnabled( TRUE );
    viewport()->tqrepaint( FALSE );
    horizontalHeader()->tqrepaint();
    verticalHeader()->tqrepaint();
    setSize( cur );
    // keep others aware
    if ( d->lastAt == -1 )
 	setCurrentSelection( -1, -1 );
    else if ( d->lastAt != currentRow() )
	setCurrentSelection( currentRow(), currentColumn() );
    if ( cur->isValid() )
	emit currentChanged( sqlCursor() );
}

/*!
    Refreshes the table. The cursor is refreshed using the current
    filter, the current sort, and the currently defined columns.
    Equivalent to calling refresh( TQDataTable::RefreshData ).
*/

void TQDataTable::refresh()
{
    refresh( RefreshData );
}

/*!
    \reimp

    Selects the record in the table using the current cursor edit
    buffer and the fields specified by the index \a idx. If \a atHint
    is specified, it will be used as a hint about where to begin
    searching.
*/

bool TQDataTable::tqfindBuffer( const TQSqlIndex& idx, int atHint )
{
    TQSqlCursor* cur = sqlCursor();
    if ( !cur )
	return FALSE;
    bool found = d->cur.tqfindBuffer( idx, atHint );
    if ( found )
	setCurrentCell( cur->at(), currentColumn() );
    return found;
}

/*! \internal
    Returns the string representation of a database field.
*/
TQString TQDataTable::fieldToString( const TQSqlField * field )
{
    TQString text;
    if ( field->isNull() ) {
	text = nullText();
    } else {
	TQVariant val = field->value();
	switch ( val.type() ) {
	    case TQVariant::Bool:
		text = val.toBool() ? d->trueTxt : d->falseTxt;
		break;
	    case TQVariant::Date:
		text = val.toDate().toString( (Qt::DateFormat)d->datefmt );
		break;
	    case TQVariant::Time:
		text = val.toTime().toString( (Qt::DateFormat)d->datefmt );
		break;
	    case TQVariant::DateTime:
		text = val.toDateTime().toString( (Qt::DateFormat)d->datefmt );
		break;
	    default:
		text = val.toString();
		break;
	}
    }
    return text;
}

/*!
    \reimp
*/

void TQDataTable::swapColumns( int col1, int col2, bool )
{
    TQString fld = d->fld[ col1 ];
    TQString fldLabel = d->fldLabel[ col1 ];
    TQIconSet fldIcon = d->fldIcon[ col1 ];
    int fldWidth = d->fldWidth[ col1 ];

    d->fld[ col1 ] = d->fld[ col2 ];
    d->fldLabel[ col1 ] = d->fldLabel[ col2 ];
    d->fldIcon[ col1 ] = d->fldIcon[ col2 ];
    d->fldWidth[ col1 ] = d->fldWidth[ col2 ];

    d->fld[ col2 ] = fld;
    d->fldLabel[ col2 ] = fldLabel;
    d->fldIcon[ col2 ] = fldIcon;
    d->fldWidth[ col2 ] = fldWidth;

    int colIndex = d->colIndex[ col1 ];
    d->colIndex[ col1 ] = d->colIndex[ col2 ];
    d->colIndex[ col2 ] = colIndex;
}

/*!
    \reimp
*/

void TQDataTable::drawContents( TQPainter * p, int cx, int cy, int cw, int ch )
{
    TQTable::drawContents( p, cx, cy, cw, ch );
    if ( sqlCursor() && currentRow() >= 0 )
	sqlCursor()->seek( currentRow() );
}

/*!
    \reimp
*/

void TQDataTable::hideColumn( int col )
{
    d->fldHidden[col] = TRUE;
    refresh( RefreshColumns );
}

/*!
    \reimp
*/

void TQDataTable::showColumn( int col )
{
    d->fldHidden[col] = FALSE;
    refresh( RefreshColumns );
}

/*!
    \fn void TQDataTable::currentChanged( TQSqlRecord* record )

    This signal is emitted whenever a new row is selected in the
    table. The \a record parameter points to the contents of the newly
    selected record.
*/

/*!
    \fn void TQDataTable::primeInsert( TQSqlRecord* buf )

    This signal is emitted after the cursor is primed for insert by
    the table, when an insert action is beginning on the table. The \a
    buf parameter points to the edit buffer being inserted. Connect to
    this signal in order to, for example, prime the record buffer with
    default data values.
*/

/*!
    \fn void TQDataTable::primeUpdate( TQSqlRecord* buf )

    This signal is emitted after the cursor is primed for update by
    the table, when an update action is beginning on the table. The \a
    buf parameter points to the edit buffer being updated. Connect to
    this signal in order to, for example, provide some visual feedback
    that the user is in 'edit mode'.
*/

/*!
    \fn void TQDataTable::primeDelete( TQSqlRecord* buf )

    This signal is emitted after the cursor is primed for delete by
    the table, when a delete action is beginning on the table. The \a
    buf parameter points to the edit buffer being deleted. Connect to
    this signal in order to, for example, record auditing information
    on deletions.
*/

/*!
    \fn void TQDataTable::beforeInsert( TQSqlRecord* buf )

    This signal is emitted just before the cursor's edit buffer is
    inserted into the database. The \a buf parameter points to the
    edit buffer being inserted. Connect to this signal to, for
    example, populate a key field with a unique sequence number.
*/

/*!
    \fn void TQDataTable::beforeUpdate( TQSqlRecord* buf )

    This signal is emitted just before the cursor's edit buffer is
    updated in the database. The \a buf parameter points to the edit
    buffer being updated. Connect to this signal when you want to
    transform the user's data behind-the-scenes.
*/

/*!
    \fn void TQDataTable::beforeDelete( TQSqlRecord* buf )

    This signal is emitted just before the currently selected record
    is deleted from the database. The \a buf parameter points to the
    edit buffer being deleted. Connect to this signal to, for example,
    copy some of the fields for later use.
*/

/*!
    \fn void TQDataTable::cursorChanged( TQSql::Op mode )

    This signal is emitted whenever the cursor record was changed due
    to an edit. The \a mode parameter is the type of edit that just
    took place.
*/

#endif