/
qcalendarwidget.cpp
3199 lines (2720 loc) · 93.4 KB
/
qcalendarwidget.cpp
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
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qcalendarwidget.h"
#include <qabstractitemmodel.h>
#include <qstyleditemdelegate.h>
#include <qdatetime.h>
#include <qtableview.h>
#include <qlayout.h>
#include <qevent.h>
#include <qtextformat.h>
#include <qheaderview.h>
#include <private/qwidget_p.h>
#include <qpushbutton.h>
#include <qtoolbutton.h>
#include <qlabel.h>
#include <qspinbox.h>
#include <qmenu.h>
#include <qapplication.h>
#include <private/qapplication_p.h>
#include <qbasictimer.h>
#include <qstylepainter.h>
#include <qcalendar.h>
#include <vector>
QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
enum {
RowCount = 6,
ColumnCount = 7,
HeaderColumn = 0,
HeaderRow = 0,
MinimumDayOffset = 1
};
static QString formatNumber(int number, int fieldWidth)
{
return QString::number(number).rightJustified(fieldWidth, u'0');
}
namespace QtPrivate {
class QCalendarDateSectionValidator
{
public:
enum Section {
NextSection,
ThisSection,
PrevSection
};
QCalendarDateSectionValidator() {}
virtual ~QCalendarDateSectionValidator() {}
virtual Section handleKey(int key) = 0;
virtual QDate applyToDate(QDate date, QCalendar cal = QCalendar()) const = 0;
virtual void setDate(QDate date, QCalendar cal = QCalendar()) = 0;
virtual QString text() const = 0;
virtual QString text(QDate date, QCalendar cal, int repeat) const = 0;
QLocale m_locale;
protected:
static QString highlightString(const QString &str, int pos);
};
QString QCalendarDateSectionValidator::highlightString(const QString &str, int pos)
{
if (pos == 0)
return "<b>"_L1 + str + "</b>"_L1;
int startPos = str.size() - pos;
return QStringView{str}.mid(0, startPos) + "<b>"_L1 + QStringView{str}.mid(startPos, pos) + "</b>"_L1;
}
class QCalendarDayValidator : public QCalendarDateSectionValidator
{
public:
QCalendarDayValidator();
virtual Section handleKey(int key) override;
virtual QDate applyToDate(QDate date, QCalendar cal) const override;
virtual void setDate(QDate date, QCalendar cal) override;
virtual QString text() const override;
virtual QString text(QDate date, QCalendar cal, int repeat) const override;
private:
int m_pos;
int m_day;
int m_oldDay;
};
QCalendarDayValidator::QCalendarDayValidator()
: QCalendarDateSectionValidator(), m_pos(0), m_day(1), m_oldDay(1)
{
}
QCalendarDateSectionValidator::Section QCalendarDayValidator::handleKey(int key)
{
if (key == Qt::Key_Right || key == Qt::Key_Left) {
m_pos = 0;
return QCalendarDateSectionValidator::ThisSection;
} else if (key == Qt::Key_Up) {
m_pos = 0;
++m_day;
if (m_day > 31)
m_day = 1;
return QCalendarDateSectionValidator::ThisSection;
} else if (key == Qt::Key_Down) {
m_pos = 0;
--m_day;
if (m_day < 1)
m_day = 31;
return QCalendarDateSectionValidator::ThisSection;
} else if (key == Qt::Key_Back || key == Qt::Key_Backspace) {
--m_pos;
if (m_pos < 0)
m_pos = 1;
if (m_pos == 0)
m_day = m_oldDay;
else
m_day = m_day / 10;
//m_day = m_oldDay / 10 * 10 + m_day / 10;
if (m_pos == 0)
return QCalendarDateSectionValidator::PrevSection;
return QCalendarDateSectionValidator::ThisSection;
}
if (key < Qt::Key_0 || key > Qt::Key_9)
return QCalendarDateSectionValidator::ThisSection;
int pressedKey = key - Qt::Key_0;
if (m_pos == 0)
m_day = pressedKey;
else
m_day = m_day % 10 * 10 + pressedKey;
if (m_day > 31)
m_day = 31;
++m_pos;
if (m_pos > 1) {
m_pos = 0;
return QCalendarDateSectionValidator::NextSection;
}
return QCalendarDateSectionValidator::ThisSection;
}
QDate QCalendarDayValidator::applyToDate(QDate date, QCalendar cal) const
{
auto parts = cal.partsFromDate(date);
if (!parts.isValid())
return QDate();
parts.day = qMin(qMax(1, m_day), cal.daysInMonth(parts.month, parts.year));
return cal.dateFromParts(parts);
}
void QCalendarDayValidator::setDate(QDate date, QCalendar cal)
{
m_day = m_oldDay = date.day(cal);
m_pos = 0;
}
QString QCalendarDayValidator::text() const
{
return highlightString(formatNumber(m_day, 2), m_pos);
}
QString QCalendarDayValidator::text(QDate date, QCalendar cal, int repeat) const
{
if (repeat <= 1) {
return QString::number(date.day(cal));
} else if (repeat == 2) {
return formatNumber(date.day(cal), 2);
} else if (repeat == 3) {
return m_locale.dayName(date.dayOfWeek(cal), QLocale::ShortFormat);
} else /* repeat >= 4 */ {
return m_locale.dayName(date.dayOfWeek(cal), QLocale::LongFormat);
}
}
//////////////////////////////////
class QCalendarMonthValidator : public QCalendarDateSectionValidator
{
public:
QCalendarMonthValidator();
virtual Section handleKey(int key) override;
virtual QDate applyToDate(QDate date, QCalendar cal) const override;
virtual void setDate(QDate date, QCalendar cal) override;
virtual QString text() const override;
virtual QString text(QDate date, QCalendar cal, int repeat) const override;
private:
int m_pos;
int m_month;
int m_oldMonth;
};
QCalendarMonthValidator::QCalendarMonthValidator()
: QCalendarDateSectionValidator(), m_pos(0), m_month(1), m_oldMonth(1)
{
}
QCalendarDateSectionValidator::Section QCalendarMonthValidator::handleKey(int key)
{
if (key == Qt::Key_Right || key == Qt::Key_Left) {
m_pos = 0;
return QCalendarDateSectionValidator::ThisSection;
} else if (key == Qt::Key_Up) {
m_pos = 0;
++m_month;
if (m_month > 12)
m_month = 1;
return QCalendarDateSectionValidator::ThisSection;
} else if (key == Qt::Key_Down) {
m_pos = 0;
--m_month;
if (m_month < 1)
m_month = 12;
return QCalendarDateSectionValidator::ThisSection;
} else if (key == Qt::Key_Back || key == Qt::Key_Backspace) {
--m_pos;
if (m_pos < 0)
m_pos = 1;
if (m_pos == 0)
m_month = m_oldMonth;
else
m_month = m_month / 10;
//m_month = m_oldMonth / 10 * 10 + m_month / 10;
if (m_pos == 0)
return QCalendarDateSectionValidator::PrevSection;
return QCalendarDateSectionValidator::ThisSection;
}
if (key < Qt::Key_0 || key > Qt::Key_9)
return QCalendarDateSectionValidator::ThisSection;
int pressedKey = key - Qt::Key_0;
if (m_pos == 0)
m_month = pressedKey;
else
m_month = m_month % 10 * 10 + pressedKey;
if (m_month > 12)
m_month = 12;
++m_pos;
if (m_pos > 1) {
m_pos = 0;
return QCalendarDateSectionValidator::NextSection;
}
return QCalendarDateSectionValidator::ThisSection;
}
QDate QCalendarMonthValidator::applyToDate(QDate date, QCalendar cal) const
{
auto parts = cal.partsFromDate(date);
if (!parts.isValid())
return QDate();
parts.month = qMin(qMax(1, m_month), cal.monthsInYear(parts.year));
parts.day = qMin(parts.day, cal.daysInMonth(m_month, parts.year)); // m_month or parts.month ?
return cal.dateFromParts(parts);
}
void QCalendarMonthValidator::setDate(QDate date, QCalendar cal)
{
m_month = m_oldMonth = date.month(cal);
m_pos = 0;
}
QString QCalendarMonthValidator::text() const
{
return highlightString(formatNumber(m_month, 2), m_pos);
}
QString QCalendarMonthValidator::text(QDate date, QCalendar cal, int repeat) const
{
const auto parts = cal.partsFromDate(date);
// Numeric forms:
if (repeat <= 1)
return QString::number(parts.month);
if (repeat == 2)
return formatNumber(parts.month, 2);
// Text forms:
if (repeat == 3)
return cal.standaloneMonthName(m_locale, parts.month, parts.year, QLocale::ShortFormat);
/* repeat >= 4 */
return cal.standaloneMonthName(m_locale, parts.month, parts.year, QLocale::LongFormat);
}
//////////////////////////////////
class QCalendarYearValidator : public QCalendarDateSectionValidator
{
public:
QCalendarYearValidator();
virtual Section handleKey(int key) override;
virtual QDate applyToDate(QDate date, QCalendar cal) const override;
virtual void setDate(QDate date, QCalendar cal) override;
virtual QString text() const override;
virtual QString text(QDate date, QCalendar cal, int repeat) const override;
private:
int pow10(int n);
int m_pos;
int m_year;
int m_oldYear;
};
QCalendarYearValidator::QCalendarYearValidator()
: QCalendarDateSectionValidator(), m_pos(0), m_year(2000), m_oldYear(2000)
{
// TODO: What to use (for non-Gregorian calendars) as default year?
// Maybe 1360 for Jalali, 1420 for Islamic, etc.
}
int QCalendarYearValidator::pow10(int n)
{
int power = 1;
for (int i = 0; i < n; i++)
power *= 10;
return power;
}
QCalendarDateSectionValidator::Section QCalendarYearValidator::handleKey(int key)
{
if (key == Qt::Key_Right || key == Qt::Key_Left) {
m_pos = 0;
return QCalendarDateSectionValidator::ThisSection;
} else if (key == Qt::Key_Up) {
m_pos = 0;
++m_year;
return QCalendarDateSectionValidator::ThisSection;
} else if (key == Qt::Key_Down) {
m_pos = 0;
--m_year;
return QCalendarDateSectionValidator::ThisSection;
} else if (key == Qt::Key_Back || key == Qt::Key_Backspace) {
--m_pos;
if (m_pos < 0)
m_pos = 3;
int pow = pow10(m_pos);
m_year = m_oldYear / pow * pow + m_year % (pow * 10) / 10;
if (m_pos == 0)
return QCalendarDateSectionValidator::PrevSection;
return QCalendarDateSectionValidator::ThisSection;
}
if (key < Qt::Key_0 || key > Qt::Key_9)
return QCalendarDateSectionValidator::ThisSection;
int pressedKey = key - Qt::Key_0;
int pow = pow10(m_pos);
m_year = m_year / (pow * 10) * (pow * 10) + m_year % pow * 10 + pressedKey;
++m_pos;
if (m_pos > 3) {
m_pos = 0;
return QCalendarDateSectionValidator::NextSection;
}
return QCalendarDateSectionValidator::ThisSection;
}
QDate QCalendarYearValidator::applyToDate(QDate date, QCalendar cal) const
{
auto parts = cal.partsFromDate(date);
if (!parts.isValid())
return QDate();
// This widget does not support negative years (some calendars may support)
parts.year = qMax(1, m_year);
parts.day = qMin(parts.day, cal.daysInMonth(parts.month, parts.year));
return cal.dateFromParts(parts);
}
void QCalendarYearValidator::setDate(QDate date, QCalendar cal)
{
m_year = m_oldYear = date.year(cal);
m_pos = 0;
}
QString QCalendarYearValidator::text() const
{
return highlightString(formatNumber(m_year, 4), m_pos);
}
QString QCalendarYearValidator::text(QDate date, QCalendar cal, int repeat) const
{
if (repeat < 4)
return formatNumber(date.year(cal) % 100, 2);
return QString::number(date.year(cal));
}
///////////////////////////////////
struct SectionToken {
constexpr SectionToken(QCalendarDateSectionValidator *v, int rep)
: validator(v), repeat(rep) {}
QCalendarDateSectionValidator *validator;
int repeat;
};
} // namespace QtPrivate
Q_DECLARE_TYPEINFO(QtPrivate::SectionToken, Q_PRIMITIVE_TYPE);
namespace QtPrivate {
class QCalendarDateValidator
{
public:
QCalendarDateValidator();
~QCalendarDateValidator();
void handleKeyEvent(QKeyEvent *keyEvent, QCalendar cal);
QString currentText(QCalendar cal) const;
QDate currentDate() const { return m_currentDate; }
void setFormat(const QString &format);
void setInitialDate(QDate date, QCalendar cal);
void setLocale(const QLocale &locale);
private:
void toNextToken();
void toPreviousToken();
void applyToDate(QCalendar cal);
int countRepeat(const QString &str, int index) const;
void clear();
QStringList m_separators;
std::vector<SectionToken> m_tokens;
QCalendarYearValidator m_yearValidator;
QCalendarMonthValidator m_monthValidator;
QCalendarDayValidator m_dayValidator;
int m_currentToken;
QDate m_initialDate;
QDate m_currentDate;
QCalendarDateSectionValidator::Section m_lastSectionMove;
};
QCalendarDateValidator::QCalendarDateValidator()
: m_currentToken(-1),
m_initialDate(QDate::currentDate()),
m_currentDate(m_initialDate),
m_lastSectionMove(QCalendarDateSectionValidator::ThisSection)
{
}
void QCalendarDateValidator::setLocale(const QLocale &locale)
{
m_yearValidator.m_locale = locale;
m_monthValidator.m_locale = locale;
m_dayValidator.m_locale = locale;
}
QCalendarDateValidator::~QCalendarDateValidator()
{
clear();
}
// from qdatetime.cpp
int QCalendarDateValidator::countRepeat(const QString &str, int index) const
{
Q_ASSERT(index >= 0 && index < str.size());
int count = 1;
const QChar ch = str.at(index);
while (index + count < str.size() && str.at(index + count) == ch)
++count;
return count;
}
void QCalendarDateValidator::setInitialDate(QDate date, QCalendar cal)
{
m_yearValidator.setDate(date, cal);
m_monthValidator.setDate(date, cal);
m_dayValidator.setDate(date, cal);
m_initialDate = date;
m_currentDate = date;
m_lastSectionMove = QCalendarDateSectionValidator::ThisSection;
}
QString QCalendarDateValidator::currentText(QCalendar cal) const
{
QString str;
const int numSeps = m_separators.size();
const int numTokens = int(m_tokens.size());
for (int i = 0; i < numSeps; ++i) {
str += m_separators.at(i);
if (i < numTokens) {
const SectionToken &token = m_tokens[i];
if (i == m_currentToken)
str += token.validator->text();
else
str += token.validator->text(m_currentDate, cal, token.repeat);
}
}
return str;
}
void QCalendarDateValidator::clear()
{
m_tokens.clear();
m_separators.clear();
m_currentToken = -1;
}
void QCalendarDateValidator::setFormat(const QString &format)
{
clear();
int pos = 0;
const auto quote = u'\'';
bool quoting = false;
QString separator;
while (pos < format.size()) {
const QStringView mid = QStringView{format}.mid(pos);
int offset = 1;
if (mid.startsWith(quote)) {
quoting = !quoting;
} else {
const QChar nextChar = format.at(pos);
if (quoting) {
separator += nextChar;
quoting = false;
} else {
QCalendarDateSectionValidator *validator = nullptr;
if (nextChar == u'd') {
offset = qMin(4, countRepeat(format, pos));
validator = &m_dayValidator;
} else if (nextChar == u'M') {
offset = qMin(4, countRepeat(format, pos));
validator = &m_monthValidator;
} else if (nextChar == u'y') {
offset = qMin(4, countRepeat(format, pos));
validator = &m_yearValidator;
} else {
separator += nextChar;
}
if (validator) {
m_tokens.push_back(SectionToken(validator, offset));
m_separators.append(separator);
separator = QString();
if (m_currentToken < 0)
m_currentToken = int(m_tokens.size()) - 1;
}
}
}
pos += offset;
}
m_separators += separator;
}
void QCalendarDateValidator::applyToDate(QCalendar cal)
{
m_currentDate = m_yearValidator.applyToDate(m_currentDate, cal);
m_currentDate = m_monthValidator.applyToDate(m_currentDate, cal);
m_currentDate = m_dayValidator.applyToDate(m_currentDate, cal);
}
void QCalendarDateValidator::toNextToken()
{
if (m_currentToken < 0)
return;
++m_currentToken;
m_currentToken %= m_tokens.size();
}
void QCalendarDateValidator::toPreviousToken()
{
if (m_currentToken < 0)
return;
--m_currentToken;
m_currentToken %= m_tokens.size();
}
void QCalendarDateValidator::handleKeyEvent(QKeyEvent *keyEvent,QCalendar cal)
{
if (m_currentToken < 0)
return;
int key = keyEvent->key();
if (m_lastSectionMove == QCalendarDateSectionValidator::NextSection) {
if (key == Qt::Key_Back || key == Qt::Key_Backspace)
toPreviousToken();
}
if (key == Qt::Key_Right)
toNextToken();
else if (key == Qt::Key_Left)
toPreviousToken();
m_lastSectionMove = m_tokens[m_currentToken].validator->handleKey(key);
applyToDate(cal);
if (m_lastSectionMove == QCalendarDateSectionValidator::NextSection)
toNextToken();
else if (m_lastSectionMove == QCalendarDateSectionValidator::PrevSection)
toPreviousToken();
}
//////////////////////////////////
class QCalendarTextNavigator: public QObject
{
Q_OBJECT
public:
QCalendarTextNavigator(QObject *parent = nullptr)
: QObject(parent), m_dateText(nullptr), m_dateFrame(nullptr), m_dateValidator(nullptr),
m_widget(nullptr), m_editDelay(1500), m_date(QDate::currentDate()) {}
QWidget *widget() const;
void setWidget(QWidget *widget);
int dateEditAcceptDelay() const;
void setDateEditAcceptDelay(int delay);
void setDate(QDate date);
bool eventFilter(QObject *o, QEvent *e) override;
void timerEvent(QTimerEvent *e) override;
signals:
void dateChanged(QDate date);
void editingFinished();
private:
void applyDate();
void updateDateLabel();
void createDateLabel();
void removeDateLabel();
QLabel *m_dateText;
QFrame *m_dateFrame;
QBasicTimer m_acceptTimer;
QCalendarDateValidator *m_dateValidator;
QWidget *m_widget;
int m_editDelay;
QDate m_date;
const QCalendar m_calendar;
};
QWidget *QCalendarTextNavigator::widget() const
{
return m_widget;
}
void QCalendarTextNavigator::setWidget(QWidget *widget)
{
m_widget = widget;
}
void QCalendarTextNavigator::setDate(QDate date)
{
m_date = date;
}
void QCalendarTextNavigator::updateDateLabel()
{
if (!m_widget)
return;
m_acceptTimer.start(m_editDelay, this);
m_dateText->setText(m_dateValidator->currentText(m_calendar));
QSize s = m_dateFrame->sizeHint();
QRect r = m_widget->geometry(); // later, just the table section
QRect newRect((r.width() - s.width()) / 2, (r.height() - s.height()) / 2, s.width(), s.height());
m_dateFrame->setGeometry(newRect);
// need to set palette after geometry update as phonestyle sets transparency
// effect in move event.
QPalette p = m_dateFrame->palette();
p.setBrush(QPalette::Window, m_dateFrame->window()->palette().brush(QPalette::Window));
m_dateFrame->setPalette(p);
m_dateFrame->raise();
m_dateFrame->show();
}
void QCalendarTextNavigator::applyDate()
{
QDate date = m_dateValidator->currentDate();
if (m_date == date)
return;
m_date = date;
emit dateChanged(date);
}
void QCalendarTextNavigator::createDateLabel()
{
if (m_dateFrame)
return;
m_dateFrame = new QFrame(m_widget);
QVBoxLayout *vl = new QVBoxLayout;
m_dateText = new QLabel;
vl->addWidget(m_dateText);
m_dateFrame->setLayout(vl);
m_dateFrame->setFrameShadow(QFrame::Plain);
m_dateFrame->setFrameShape(QFrame::Box);
m_dateValidator = new QCalendarDateValidator();
m_dateValidator->setLocale(m_widget->locale());
m_dateValidator->setFormat(m_widget->locale().dateFormat(QLocale::ShortFormat));
m_dateValidator->setInitialDate(m_date, m_calendar);
m_dateFrame->setAutoFillBackground(true);
m_dateFrame->setBackgroundRole(QPalette::Window);
}
void QCalendarTextNavigator::removeDateLabel()
{
if (!m_dateFrame)
return;
m_acceptTimer.stop();
m_dateFrame->hide();
m_dateFrame->deleteLater();
delete m_dateValidator;
m_dateFrame = nullptr;
m_dateText = nullptr;
m_dateValidator = nullptr;
}
bool QCalendarTextNavigator::eventFilter(QObject *o, QEvent *e)
{
if (m_widget) {
if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease) {
QKeyEvent *ke = static_cast<QKeyEvent *>(e);
if ((ke->text().size() > 0 && ke->text().at(0).isPrint()) || m_dateFrame) {
if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Select) {
applyDate();
emit editingFinished();
removeDateLabel();
#if QT_CONFIG(shortcut)
} else if (ke->matches(QKeySequence::Cancel)) {
removeDateLabel();
#endif
} else if (e->type() == QEvent::KeyPress) {
createDateLabel();
m_dateValidator->handleKeyEvent(ke, m_calendar);
updateDateLabel();
}
ke->accept();
return true;
}
// If we are navigating let the user finish his date in old locate.
// If we change our mind and want it to update immediately simply uncomment below
/*
} else if (e->type() == QEvent::LocaleChange) {
if (m_dateValidator) {
m_dateValidator->setLocale(m_widget->locale());
m_dateValidator->setFormat(m_widget->locale().dateFormat(QLocale::ShortFormat));
updateDateLabel();
}
*/
}
}
return QObject::eventFilter(o,e);
}
void QCalendarTextNavigator::timerEvent(QTimerEvent *e)
{
if (e->timerId() == m_acceptTimer.timerId()) {
applyDate();
removeDateLabel();
}
}
int QCalendarTextNavigator::dateEditAcceptDelay() const
{
return m_editDelay;
}
void QCalendarTextNavigator::setDateEditAcceptDelay(int delay)
{
m_editDelay = delay;
}
class QCalendarView;
// a small helper class that replaces a QMap<Qt::DayOfWeek, T>,
// but requires T to have a member-swap and a default constructor
// which should be cheap (no memory allocations)
QT_WARNING_PUSH
QT_WARNING_DISABLE_MSVC(4351) // "new behavior: elements of array ... will be default initialized"
template <typename T>
class StaticDayOfWeekAssociativeArray {
bool contained[7];
T data[7];
static constexpr int day2idx(Qt::DayOfWeek day) noexcept { return int(day) - 1; } // alt: day % 7
public:
constexpr StaticDayOfWeekAssociativeArray() noexcept(noexcept(T()))
: contained{}, data{} // arrays require uniform initialization
{}
constexpr bool contains(Qt::DayOfWeek day) const noexcept { return contained[day2idx(day)]; }
constexpr const T &value(Qt::DayOfWeek day) const noexcept { return data[day2idx(day)]; }
constexpr T &operator[](Qt::DayOfWeek day) noexcept
{
const int idx = day2idx(day);
contained[idx] = true;
return data[idx];
}
constexpr void insert(Qt::DayOfWeek day, T v) noexcept
{
operator[](day).swap(v);
}
};
QT_WARNING_POP
class QCalendarModel : public QAbstractTableModel
{
Q_OBJECT
public:
QCalendarModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent) const override
{
if (parent.isValid())
return 0;
return RowCount + m_firstRow;
}
int columnCount(const QModelIndex &parent) const override
{
if (parent.isValid())
return 0;
return ColumnCount + m_firstColumn;
}
QVariant data(const QModelIndex &index, int role) const override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
void showMonth(int year, int month);
void setDate(QDate d);
void setCalendar(QCalendar c);
QCalendar calendar() const;
void setMinimumDate(QDate date);
void setMaximumDate(QDate date);
void setRange(QDate min, QDate max);
void setHorizontalHeaderFormat(QCalendarWidget::HorizontalHeaderFormat format);
void setFirstColumnDay(Qt::DayOfWeek dayOfWeek);
Qt::DayOfWeek firstColumnDay() const;
bool weekNumbersShown() const;
void setWeekNumbersShown(bool show);
QTextCharFormat formatForCell(int row, int col) const;
Qt::DayOfWeek dayOfWeekForColumn(int section) const;
int columnForDayOfWeek(Qt::DayOfWeek day) const;
QDate dateForCell(int row, int column) const;
void cellForDate(QDate date, int *row, int *column) const;
QString dayName(Qt::DayOfWeek day) const;
void setView(QCalendarView *view)
{ m_view = view; }
void internalUpdate();
QDate referenceDate() const;
int columnForFirstOfMonth(QDate date) const;
QString monthName(const QLocale &locale, int month)
{
return m_calendar.standaloneMonthName(locale, month, m_shownYear, QLocale::LongFormat);
}
int m_firstColumn;
int m_firstRow;
QCalendar m_calendar;
QDate m_date;
QDate m_minimumDate;
QDate m_maximumDate;
int m_shownYear;
int m_shownMonth;
Qt::DayOfWeek m_firstDay;
QCalendarWidget::HorizontalHeaderFormat m_horizontalHeaderFormat;
bool m_weekNumbersShown;
StaticDayOfWeekAssociativeArray<QTextCharFormat> m_dayFormats;
QMap<QDate, QTextCharFormat> m_dateFormats;
QTextCharFormat m_headerFormat;
QCalendarView *m_view;
};
class QCalendarView : public QTableView
{
Q_OBJECT
public:
QCalendarView(QWidget *parent = nullptr);
void internalUpdate() { updateGeometries(); }
void setReadOnly(bool enable);
virtual void keyboardSearch(const QString &) override {}
signals:
void showDate(QDate date);
void changeDate(QDate date, bool changeMonth);
void clicked(QDate date);
void editingFinished();
protected:
QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
#if QT_CONFIG(wheelevent)
void wheelEvent(QWheelEvent *event) override;
#endif
void keyPressEvent(QKeyEvent *event) override;
bool event(QEvent *event) override;
QDate handleMouseEvent(QMouseEvent *event);
public:
bool readOnly;
private:
bool validDateClicked;
#ifdef QT_KEYPAD_NAVIGATION
QDate origDate;
#endif
};
QCalendarModel::QCalendarModel(QObject *parent)
: QAbstractTableModel(parent),
m_firstColumn(1),
m_firstRow(1),
m_date(QDate::currentDate()),
m_minimumDate(QDate::fromJulianDay(1)),
m_maximumDate(9999, 12, 31),
m_shownYear(m_date.year(m_calendar)),
m_shownMonth(m_date.month(m_calendar)),
m_firstDay(QLocale().firstDayOfWeek()),
m_horizontalHeaderFormat(QCalendarWidget::ShortDayNames),
m_weekNumbersShown(true),
m_view(nullptr)
{
}
Qt::DayOfWeek QCalendarModel::dayOfWeekForColumn(int column) const
{
int col = column - m_firstColumn;
if (col < 0 || col > 6)
return Qt::Sunday;
int day = m_firstDay + col;
if (day > 7)
day -= 7;
return Qt::DayOfWeek(day);
}
int QCalendarModel::columnForDayOfWeek(Qt::DayOfWeek day) const
{
if (day < 1 || unsigned(day) > unsigned(7))
return -1;
int column = (int)day - (int)m_firstDay;
if (column < 0)
column += 7;
return column + m_firstColumn;
}
/*
This simple algorithm tries to generate a valid date from the month shown.
Some months don't contain a first day (e.g. Jan of -4713 year,
so QDate (-4713, 1, 1) would be invalid). In that case we try to generate
another valid date for that month. Later, returned date's day is the number of cells
calendar widget will reserve for days before referenceDate. (E.g. if returned date's
day is 16, that day will be placed in 3rd or 4th row, not in the 1st or 2nd row).
Depending on referenceData we can change behaviour of Oct 1582. If referenceDate is 1st
of Oct we render 1 Oct in 1st or 2nd row. If referenceDate is 17 of Oct we show always 16
dates before 17 of Oct, and since this month contains the hole 5-14 Oct, the first of Oct
will be rendered in 2nd or 3rd row, showing more dates from previous month.
*/
QDate QCalendarModel::referenceDate() const
{
// TODO: Check this
int refDay = 1;
while (refDay <= 31) {
QDate refDate(m_shownYear, m_shownMonth, refDay, m_calendar);
if (refDate.isValid())
return refDate;
refDay += 1;
}
return QDate();
}
int QCalendarModel::columnForFirstOfMonth(QDate date) const
{
return (columnForDayOfWeek(static_cast<Qt::DayOfWeek>(m_calendar.dayOfWeek(date)))