1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the documentation of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 **   * Redistributions of source code must retain the above copyright
25 **     notice, this list of conditions and the following disclaimer.
26 **   * Redistributions in binary form must reproduce the above copyright
27 **     notice, this list of conditions and the following disclaimer in
28 **     the documentation and/or other materials provided with the
29 **     distribution.
30 **   * Neither the name of The Qt Company Ltd nor the names of its
31 **     contributors may be used to endorse or promote products derived
32 **     from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50 
51 //! [0]
52 label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
53 label->setAlignment({ });
54 //! [0]
55 
56 
57 //! [1]
58 class MyClass
59 {
60 public:
61     enum Option {
62         NoOptions = 0x0,
63         ShowTabs = 0x1,
64         ShowAll = 0x2,
65         SqueezeBlank = 0x4
66     };
67     Q_DECLARE_FLAGS(Options, Option)
68     ...
69 };
70 
71 Q_DECLARE_OPERATORS_FOR_FLAGS(MyClass::Options)
72 //! [1]
73 
74 //! [meta-object flags]
75 Q_FLAG(Options)
76 //! [meta-object flags]
77 
78 //! [2]
79 typedef QFlags<Enum> Flags;
80 //! [2]
81 
82 
83 //! [3]
84 int myValue = 10;
85 int minValue = 2;
86 int maxValue = 6;
87 
88 int boundedValue = qBound(minValue, myValue, maxValue);
89 // boundedValue == 6
90 //! [3]
91 
92 
93 //! [4]
94 if (!driver()->isOpen() || driver()->isOpenError()) {
95     qWarning("QSqlQuery::exec: database not open");
96     return false;
97 }
98 //! [4]
99 
100 
101 //! [5]
102 qint64 value = Q_INT64_C(932838457459459);
103 //! [5]
104 
105 
106 //! [6]
107 quint64 value = Q_UINT64_C(932838457459459);
108 //! [6]
109 
110 
111 //! [7]
112 void myMsgHandler(QtMsgType, const char *);
113 //! [7]
114 
115 
116 //! [8]
117 qint64 value = Q_INT64_C(932838457459459);
118 //! [8]
119 
120 
121 //! [9]
122 quint64 value = Q_UINT64_C(932838457459459);
123 //! [9]
124 
125 
126 //! [10]
127 int absoluteValue;
128 int myValue = -4;
129 
130 absoluteValue = qAbs(myValue);
131 // absoluteValue == 4
132 //! [10]
133 
134 
135 //! [11A]
136 double valueA = 2.3;
137 double valueB = 2.7;
138 
139 int roundedValueA = qRound(valueA);
140 // roundedValueA = 2
141 int roundedValueB = qRound(valueB);
142 // roundedValueB = 3
143 //! [11A]
144 
145 //! [11B]
146 float valueA = 2.3;
147 float valueB = 2.7;
148 
149 int roundedValueA = qRound(valueA);
150 // roundedValueA = 2
151 int roundedValueB = qRound(valueB);
152 // roundedValueB = 3
153 //! [11B]
154 
155 
156 //! [12A]
157 double valueA = 42949672960.3;
158 double valueB = 42949672960.7;
159 
160 qint64 roundedValueA = qRound64(valueA);
161 // roundedValueA = 42949672960
162 qint64 roundedValueB = qRound64(valueB);
163 // roundedValueB = 42949672961
164 //! [12A]
165 
166 //! [12B]
167 float valueA = 42949672960.3;
168 float valueB = 42949672960.7;
169 
170 qint64 roundedValueA = qRound64(valueA);
171 // roundedValueA = 42949672960
172 qint64 roundedValueB = qRound64(valueB);
173 // roundedValueB = 42949672961
174 //! [12B]
175 
176 
177 //! [13]
178 int myValue = 6;
179 int yourValue = 4;
180 
181 int minValue = qMin(myValue, yourValue);
182 // minValue == yourValue
183 //! [13]
184 
185 
186 //! [14]
187 int myValue = 6;
188 int yourValue = 4;
189 
190 int maxValue = qMax(myValue, yourValue);
191 // maxValue == myValue
192 //! [14]
193 
194 
195 //! [15]
196 int myValue = 10;
197 int minValue = 2;
198 int maxValue = 6;
199 
200 int boundedValue = qBound(minValue, myValue, maxValue);
201 // boundedValue == 6
202 //! [15]
203 
204 
205 //! [16]
206 #if QT_VERSION >= 0x040100
207     QIcon icon = style()->standardIcon(QStyle::SP_TrashIcon);
208 #else
209     QPixmap pixmap = style()->standardPixmap(QStyle::SP_TrashIcon);
210     QIcon icon(pixmap);
211 #endif
212 //! [16]
213 
214 
215 //! [17]
216 // File: div.cpp
217 
218 #include <QtGlobal>
219 
divide(int a,int b)220 int divide(int a, int b)
221 {
222     Q_ASSERT(b != 0);
223     return a / b;
224 }
225 //! [17]
226 
227 
228 //! [18]
229 ASSERT: "b != 0" in file div.cpp, line 7
230 //! [18]
231 
232 
233 //! [19]
234 // File: div.cpp
235 
236 #include <QtGlobal>
237 
238 int divide(int a, int b)
239 {
240     Q_ASSERT_X(b != 0, "divide", "division by zero");
241     return a / b;
242 }
243 //! [19]
244 
245 
246 //! [20]
247 ASSERT failure in divide: "division by zero", file div.cpp, line 7
248 //! [20]
249 
250 
251 //! [21]
252 int *a;
253 
254 Q_CHECK_PTR(a = new int[80]);   // WRONG!
255 
256 a = new (nothrow) int[80];      // Right
257 Q_CHECK_PTR(a);
258 //! [21]
259 
260 
261 //! [22]
262 template<typename TInputType>
myMin(const TInputType & value1,const TInputType & value2)263 const TInputType &myMin(const TInputType &value1, const TInputType &value2)
264 {
265     qDebug() << Q_FUNC_INFO << "was called with value1:" << value1 << "value2:" << value2;
266 
267     if(value1 < value2)
268         return value1;
269     else
270         return value2;
271 }
272 //! [22]
273 
274 
275 //! [23]
276 #include <qapplication.h>
277 #include <stdio.h>
278 #include <stdlib.h>
279 
myMessageOutput(QtMsgType type,const QMessageLogContext & context,const QString & msg)280 void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
281 {
282     QByteArray localMsg = msg.toLocal8Bit();
283     const char *file = context.file ? context.file : "";
284     const char *function = context.function ? context.function : "";
285     switch (type) {
286     case QtDebugMsg:
287         fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
288         break;
289     case QtInfoMsg:
290         fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
291         break;
292     case QtWarningMsg:
293         fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
294         break;
295     case QtCriticalMsg:
296         fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
297         break;
298     case QtFatalMsg:
299         fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
300         break;
301     }
302 }
303 
main(int argc,char ** argv)304 int main(int argc, char **argv)
305 {
306     qInstallMessageHandler(myMessageOutput);
307     QApplication app(argc, argv);
308     ...
309     return app.exec();
310 }
311 //! [23]
312 
313 
314 //! [24]
315 qDebug("Items in list: %d", myList.size());
316 //! [24]
317 
318 
319 //! [25]
320 qDebug() << "Brush:" << myQBrush << "Other value:" << i;
321 //! [25]
322 
323 
324 //! [qInfo_printf]
325 qInfo("Items in list: %d", myList.size());
326 //! [qInfo_printf]
327 
328 //! [qInfo_stream]
329 qInfo() << "Brush:" << myQBrush << "Other value:" << i;
330 //! [qInfo_stream]
331 
332 //! [26]
f(int c)333 void f(int c)
334 {
335     if (c > 200)
336         qWarning("f: bad argument, c == %d", c);
337 }
338 //! [26]
339 
340 
341 //! [27]
342 qWarning() << "Brush:" << myQBrush << "Other value:"
343 << i;
344 //! [27]
345 
346 
347 //! [28]
load(const QString & fileName)348 void load(const QString &fileName)
349 {
350     QFile file(fileName);
351     if (!file.exists())
352         qCritical("File '%s' does not exist!", qUtf8Printable(fileName));
353 }
354 //! [28]
355 
356 
357 //! [29]
358 qCritical() << "Brush:" << myQBrush << "Other
359 value:" << i;
360 //! [29]
361 
362 
363 //! [30]
divide(int a,int b)364 int divide(int a, int b)
365 {
366     if (b == 0)                                // program error
367         qFatal("divide: cannot divide by zero");
368     return a / b;
369 }
370 //! [30]
371 
372 
373 //! [31]
374 forever {
375     ...
376 }
377 //! [31]
378 
379 
380 //! [32]
381 CONFIG += no_keywords
382 //! [32]
383 
384 
385 //! [33]
386 CONFIG += no_keywords
387 //! [33]
388 
389 
390 //! [34]
391 QString FriendlyConversation::greeting(int type)
392 {
393     static const char *greeting_strings[] = {
394         QT_TR_NOOP("Hello"),
395         QT_TR_NOOP("Goodbye")
396     };
397     return tr(greeting_strings[type]);
398 }
399 //! [34]
400 
401 
402 //! [35]
403 static const char *greeting_strings[] = {
404     QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"),
405     QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye")
406 };
407 
greeting(int type)408 QString FriendlyConversation::greeting(int type)
409 {
410     return tr(greeting_strings[type]);
411 }
412 
global_greeting(int type)413 QString global_greeting(int type)
414 {
415     return qApp->translate("FriendlyConversation",
416                            greeting_strings[type]);
417 }
418 //! [35]
419 
420 
421 //! [36]
422 
423 static { const char *source; const char *comment; } greeting_strings[] =
424 {
425     QT_TRANSLATE_NOOP3("FriendlyConversation", "Hello",
426                        "A really friendly hello"),
427     QT_TRANSLATE_NOOP3("FriendlyConversation", "Goodbye",
428                        "A really friendly goodbye")
429 };
430 
greeting(int type)431 QString FriendlyConversation::greeting(int type)
432 {
433     return tr(greeting_strings[type].source,
434               greeting_strings[type].comment);
435 }
436 
global_greeting(int type)437 QString global_greeting(int type)
438 {
439     return qApp->translate("FriendlyConversation",
440                            greeting_strings[type].source,
441                            greeting_strings[type].comment);
442 }
443 //! [36]
444 
445 
446 //! [qttrnnoop]
447 static const char * const StatusClass::status_strings[] = {
448     QT_TR_N_NOOP("There are %n new message(s)"),
449     QT_TR_N_NOOP("There are %n total message(s)")
450 };
451 
status(int type,int count)452 QString StatusClass::status(int type, int count)
453 {
454     return tr(status_strings[type], nullptr, count);
455 }
456 //! [qttrnnoop]
457 
458 //! [qttranslatennoop]
459 static const char * const greeting_strings[] = {
460     QT_TRANSLATE_N_NOOP("Welcome Msg", "Hello, you have %n message(s)"),
461     QT_TRANSLATE_N_NOOP("Welcome Msg", "Hi, you have %n message(s)")
462 };
463 
global_greeting(int type,int msgcnt)464 QString global_greeting(int type, int msgcnt)
465 {
466     return translate("Welcome Msg", greeting_strings[type], nullptr, msgcnt);
467 }
468 //! [qttranslatennoop]
469 
470 //! [qttranslatennoop3]
471 static { const char * const source; const char * const comment; } status_strings[] = {
472     QT_TRANSLATE_N_NOOP3("Message Status", "Hello, you have %n message(s)",
473                          "A login message status"),
474     QT_TRANSLATE_N_NOOP3("Message status", "You have %n new message(s)",
475                          "A new message query status")
476 };
477 
greeting(int type,int count)478 QString FriendlyConversation::greeting(int type, int count)
479 {
480     return tr(status_strings[type].source,
481               status_strings[type].comment, count);
482 }
483 
global_greeting(int type,int count)484 QString global_greeting(int type, int count)
485 {
486     return qApp->translate("Message Status",
487                            status_strings[type].source,
488                            status_strings[type].comment,
489                            count);
490 }
491 //! [qttranslatennoop3]
492 
493 
494 //! [qttrid]
495     //% "%n fooish bar(s) found.\n"
496     //% "Do you want to continue?"
497     QString text = qtTrId("qtn_foo_bar", n);
498 //! [qttrid]
499 
500 
501 //! [qttrid_noop]
502 static const char * const ids[] = {
503     //% "This is the first text."
504     QT_TRID_NOOP("qtn_1st_text"),
505     //% "This is the second text."
506     QT_TRID_NOOP("qtn_2nd_text"),
507     0
508 };
509 
addLabels()510 void TheClass::addLabels()
511 {
512     for (int i = 0; ids[i]; ++i)
513         new QLabel(qtTrId(ids[i]), this);
514 }
515 //! [qttrid_noop]
516 
517 
518 //! [37]
519 qWarning("%s: %s", qUtf8Printable(key), qUtf8Printable(value));
520 //! [37]
521 
522 
523 //! [qUtf16Printable]
524 qWarning("%ls: %ls", qUtf16Printable(key), qUtf16Printable(value));
525 //! [qUtf16Printable]
526 
527 
528 //! [38]
529 struct Point2D
530 {
531     int x;
532     int y;
533 };
534 
535 Q_DECLARE_TYPEINFO(Point2D, Q_PRIMITIVE_TYPE);
536 //! [38]
537 
538 
539 //! [39]
540 class Point2D
541 {
542 public:
Point2D()543     Point2D() { data = new int[2]; }
Point2D(const Point2D & other)544     Point2D(const Point2D &other) { ... }
~Point2D()545     ~Point2D() { delete[] data; }
546 
operator =(const Point2D & other)547     Point2D &operator=(const Point2D &other) { ... }
548 
x() const549     int x() const { return data[0]; }
y() const550     int y() const { return data[1]; }
551 
552 private:
553     int *data;
554 };
555 
556 Q_DECLARE_TYPEINFO(Point2D, Q_MOVABLE_TYPE);
557 //! [39]
558 
559 
560 //! [40]
561 #if Q_BYTE_ORDER == Q_BIG_ENDIAN
562 ...
563 #endif
564 
565 or
566 
567 #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
568 ...
569 #endif
570 
571 //! [40]
572 
573 
574 //! [41]
575 
576 #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
577 ...
578 #endif
579 
580 //! [41]
581 
582 
583 //! [42]
584 #if Q_BYTE_ORDER == Q_BIG_ENDIAN
585 ...
586 #endif
587 
588 //! [42]
589 
590 //! [begin namespace macro]
591 namespace QT_NAMESPACE {
592 //! [begin namespace macro]
593 
594 //! [end namespace macro]
595 }
596 //! [end namespace macro]
597 
598 //! [43]
599 class MyClass : public QObject
600 {
601 private:
602     Q_DISABLE_COPY(MyClass)
603 };
604 
605 //! [43]
606 
607 //! [44]
608 class MyClass : public QObject
609 {
610 private:
611     MyClass(const MyClass &) = delete;
612     MyClass &operator=(const MyClass &) = delete;
613 };
614 //! [44]
615 
616 //! [45]
617 QWidget w = QWidget();
618 //! [45]
619 
620 //! [46]
621 // Instead of comparing with 0.0
622 qFuzzyCompare(0.0, 1.0e-200); // This will return false
623 // Compare adding 1 to both values will fix the problem
624 qFuzzyCompare(1 + 0.0, 1 + 1.0e-200); // This will return true
625 //! [46]
626 
627 //! [47]
628 CApaApplication *myApplicationFactory();
629 //! [47]
630 
631 
632 //! [49]
633 void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &);
634 //! [49]
635 
636 //! [50]
637 class B {...};
638 class C {...};
639 class D {...};
640 struct A : public B {
641     C c;
642     D d;
643 };
644 //! [50]
645 
646 //! [51]
647 template<> class QTypeInfo<A> : public QTypeInfoMerger<A, B, C, D> {};
648 //! [51]
649 
650 //! [52]
651     struct Foo {
652         void overloadedFunction();
653         void overloadedFunction(int, const QString &);
654     };
655     ... qOverload<>(&Foo::overloadedFunction)
656     ... qOverload<int, const QString &>(&Foo::overloadedFunction)
657 //! [52]
658 
659 //! [53]
660     ... QOverload<>::of(&Foo::overloadedFunction)
661     ... QOverload<int, const QString &>::of(&Foo::overloadedFunction)
662 //! [53]
663 
664 //! [54]
665     struct Foo {
666         void overloadedFunction(int, const QString &);
667         void overloadedFunction(int, const QString &) const;
668     };
669     ... qConstOverload<int, const QString &>(&Foo::overloadedFunction)
670     ... qNonConstOverload<int, const QString &>(&Foo::overloadedFunction)
671 //! [54]
672 
673 //! [qlikely]
674     // the condition inside the "if" will be successful most of the times
675     for (int i = 1; i <= 365; i++) {
676         if (Q_LIKELY(isWorkingDay(i))) {
677             ...
678         }
679         ...
680     }
681 //! [qlikely]
682 
683 //! [qunlikely]
readConfiguration(const QFile & file)684 bool readConfiguration(const QFile &file)
685 {
686     // We expect to be asked to read an existing file
687     if (Q_UNLIKELY(!file.exists())) {
688         qWarning() << "File not found";
689         return false;
690     }
691 
692     ...
693     return true;
694 }
695 //! [qunlikely]
696 
697 //! [qunreachable-enum]
698    enum Shapes {
699        Rectangle,
700        Triangle,
701        Circle,
702        NumShapes
703    };
704 //! [qunreachable-enum]
705 
706 //! [qunreachable-switch]
707    switch (shape) {
708        case Rectangle:
709            return rectangle();
710        case Triangle:
711            return triangle();
712        case Circle:
713            return circle();
714        case NumShapes:
715            Q_UNREACHABLE();
716            break;
717    }
718 //! [qunreachable-switch]
719 
720 //! [qt-version-check]
721 #include <QtGlobal>
722 
723 #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
724 #include <QtWidgets>
725 #else
726 #include <QtGui>
727 #endif
728 //! [qt-version-check]
729 
730 //! [is-empty]
731     qgetenv(varName).isEmpty()
732 //! [is-empty]
733 
734 //! [to-int]
735     qgetenv(varName).toInt(ok, 0)
736 //! [to-int]
737 
738 //! [is-null]
739     !qgetenv(varName).isNull()
740 //! [is-null]
741 
742 //! [as-const-0]
743     QString s = ...;
744     for (QChar ch : s) // detaches 's' (performs a deep-copy if 's' was shared)
745         process(ch);
746     for (QChar ch : qAsConst(s)) // ok, no detach attempt
747         process(ch);
748 //! [as-const-0]
749 
750 //! [as-const-1]
751     const QString s = ...;
752     for (QChar ch : s) // ok, no detach attempt on const objects
753         process(ch);
754 //! [as-const-1]
755 
756 //! [as-const-2]
757     for (QChar ch : funcReturningQString())
758         process(ch); // OK, the returned object is kept alive for the loop's duration
759 //! [as-const-2]
760 
761 //! [as-const-3]
762     for (QChar ch : qAsConst(funcReturningQString()))
763         process(ch); // ERROR: ch is copied from deleted memory
764 //! [as-const-3]
765 
766 //! [as-const-4]
767     for (QChar ch : qAsConst(funcReturningQString()))
768         process(ch); // ERROR: ch is copied from deleted memory
769 //! [as-const-4]
770 
771 //! [qterminate]
772     try { expr; } catch(...) { qTerminate(); }
773 //! [qterminate]
774 
775 //! [qdecloverride]
776     // generate error if this doesn't actually override anything:
777     virtual void MyWidget::paintEvent(QPaintEvent*) override;
778 //! [qdecloverride]
779 
780 //! [qdeclfinal-1]
781     // more-derived classes no longer permitted to override this:
782     virtual void MyWidget::paintEvent(QPaintEvent*) final;
783 //! [qdeclfinal-1]
784 
785 //! [qdeclfinal-2]
786     class QRect final { // cannot be derived from
787         // ...
788     };
789 //! [qdeclfinal-2]
790