diff options
Diffstat (limited to 'src/corelib/doc/snippets/code')
48 files changed, 505 insertions, 713 deletions
diff --git a/src/corelib/doc/snippets/code/doc_src_containers.cpp b/src/corelib/doc/snippets/code/doc_src_containers.cpp index 51d369d1d5..b568462492 100644 --- a/src/corelib/doc/snippets/code/doc_src_containers.cpp +++ b/src/corelib/doc/snippets/code/doc_src_containers.cpp @@ -1,6 +1,8 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +#undef QT_NO_FOREACH // this file contains unported legacy Q_FOREACH uses + //! [0] class Employee { @@ -16,10 +18,30 @@ private: }; //! [0] +//! [range_for] +QList<QString> list = {"A", "B", "C", "D"}; +for (const auto &item : list) { + ... +} +//! [range_for] + +//! [range_for_as_const] +QList<QString> list = {"A", "B", "C", "D"}; +for (const auto &item : std::as_const(list)) { + ... +} +//! [range_for_as_const] + +//! [index] +QList<QString> list = {"A", "B", "C", "D"}; +for (qsizetype i = 0; i < list.size(); ++i) { + const auto &item = list.at(i); + ... +} +//! [index] //! [1] -QList<QString> list; -list << "A" << "B" << "C" << "D"; +QList<QString> list = {"A", "B", "C", "D"}; QListIterator<QString> i(list); while (i.hasNext()) @@ -71,11 +93,12 @@ while (i.hasNext()) //! [7] -QMap<QString, QString> map; -map.insert("Paris", "France"); -map.insert("Guatemala City", "Guatemala"); -map.insert("Mexico City", "Mexico"); -map.insert("Moscow", "Russia"); +QMap<QString, QString> map = { + {"Paris", "France"}, + {"Guatemala City", "Guatemala"}, + {"Mexico City", "Mexico"}, + {"Moscow", "Russia"} +}; ... QMutableMapIterator<QString, QString> i(map); @@ -106,28 +129,23 @@ while (i.findNext(widget)) //! [10] -QList<QString> list; -list << "A" << "B" << "C" << "D"; +QList<QString> list = {"A", "B", "C", "D"}; -QList<QString>::iterator i; -for (i = list.begin(); i != list.end(); ++i) +for (auto i = list.begin(), end = list.end(); i != end; ++i) *i = (*i).toLower(); //! [10] //! [11] -QList<QString> list; -list << "A" << "B" << "C" << "D"; +QList<QString> list = {"A", "B", "C", "D"}; -QList<QString>::reverse_iterator i; -for (i = list.rbegin(); i != list.rend(); ++i) +for (auto i = list.rbegin(), rend = list.rend(); i != rend; ++i) *i = i->toLower(); //! [11] //! [12] -QList<QString>::const_iterator i; -for (i = list.constBegin(); i != list.constEnd(); ++i) +for (auto i = list.cbegin(), end = list.cend(); i != end; ++i) qDebug() << *i; //! [12] @@ -135,8 +153,7 @@ for (i = list.constBegin(); i != list.constEnd(); ++i) //! [13] QMap<int, int> map; ... -QMap<int, int>::const_iterator i; -for (i = map.constBegin(); i != map.constEnd(); ++i) +for (auto i = map.cbegin(), end = map.cend(); i != end; ++i) qDebug() << i.key() << ':' << i.value(); //! [13] @@ -144,13 +161,11 @@ for (i = map.constBegin(); i != map.constEnd(); ++i) //! [14] // RIGHT const QList<int> sizes = splitter->sizes(); -QList<int>::const_iterator i; -for (i = sizes.begin(); i != sizes.end(); ++i) +for (auto i = sizes.begin(), end = sizes.end(); i != end; ++i) ... // WRONG -QList<int>::const_iterator i; -for (i = splitter->sizes().begin(); +for (auto i = splitter->sizes().begin(); i != splitter->sizes().end(); ++i) ... //! [14] @@ -213,13 +228,6 @@ foreach (const QString &str, map.uniqueKeys()) { //! [20] -//! [21] -forever { - ... -} -//! [21] - - //! [22] CONFIG += no_keywords //! [22] @@ -234,9 +242,9 @@ target_compile_definitions(my_app PRIVATE QT_NO_KEYWORDS) QString onlyLetters(const QString &in) { QString out; - for (int j = 0; j < in.size(); ++j) { - if (in[j].isLetter()) - out += in[j]; + for (qsizetype j = 0; j < in.size(); ++j) { + if (in.at(j).isLetter()) + out += in.at(j); } return out; } @@ -273,15 +281,15 @@ int j = *i; // Undefined behavior! //! [24] //! [25] -QList<int> list { 1, 2, 3, 4, 4, 5 }; -QSet<int> set(list.begin(), list.end()); +QList<int> list = {1, 2, 3, 4, 4, 5}; +QSet<int> set(list.cbegin(), list.cend()); /* Will generate a QSet containing 1, 2, 3, 4, 5. */ //! [25] //! [26] -QList<int> list { 2, 3, 1 }; +QList<int> list = {2, 3, 1}; std::sort(list.begin(), list.end()); /* diff --git a/src/corelib/doc/snippets/code/doc_src_properties.cpp b/src/corelib/doc/snippets/code/doc_src_properties.cpp index bb369e6456..190a843710 100644 --- a/src/corelib/doc/snippets/code/doc_src_properties.cpp +++ b/src/corelib/doc/snippets/code/doc_src_properties.cpp @@ -68,6 +68,9 @@ public: void setPriority(Priority priority) { + if (m_priority == priority) + return; + m_priority = priority; emit priorityChanged(priority); } @@ -93,7 +96,7 @@ object->setProperty("priority", "VeryHigh"); //! [7] -Q_CLASSINFO("Version", "3.0.0") +Q_CLASSINFO("DefaultProperty", "content") //! [7] //! [8] diff --git a/src/corelib/doc/snippets/code/doc_src_qalgorithms.cpp b/src/corelib/doc/snippets/code/doc_src_qalgorithms.cpp index 201517aa2a..f2b94a7416 100644 --- a/src/corelib/doc/snippets/code/doc_src_qalgorithms.cpp +++ b/src/corelib/doc/snippets/code/doc_src_qalgorithms.cpp @@ -1,15 +1,6 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause -//! [0] -double pi = 3.14; -double e = 2.71; - -qSwap(pi, e); -// pi == 2.71, e == 3.14 -//! [0] - - //! [1] QList<Employee *> list; list.append(new Employee("Blackpool", "Stephen")); diff --git a/src/corelib/doc/snippets/code/doc_src_qiterator.cpp b/src/corelib/doc/snippets/code/doc_src_qiterator.cpp index f033a7e1bb..0d921b87e6 100644 --- a/src/corelib/doc/snippets/code/doc_src_qiterator.cpp +++ b/src/corelib/doc/snippets/code/doc_src_qiterator.cpp @@ -25,15 +25,6 @@ while (i.hasNext()) float f = i.next(); //! [6] - -//! [7] -QSetIterator<QString> i(set); -i.toBack(); -while (i.hasPrevious()) - QString s = i.previous(); -//! [7] - - //! [8] QList<float> list; ... diff --git a/src/corelib/doc/snippets/code/doc_src_qnamespace.qdoc b/src/corelib/doc/snippets/code/doc_src_qnamespace.qdoc index 41fc57df40..6ce29308f1 100644 --- a/src/corelib/doc/snippets/code/doc_src_qnamespace.qdoc +++ b/src/corelib/doc/snippets/code/doc_src_qnamespace.qdoc @@ -1,5 +1,5 @@ // Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only //! [0] QObject::connect: Cannot queue arguments of type 'MyType' diff --git a/src/corelib/doc/snippets/code/doc_src_qplugin.cpp b/src/corelib/doc/snippets/code/doc_src_qplugin.cpp index 2d6e4a430f..3bca27b966 100644 --- a/src/corelib/doc/snippets/code/doc_src_qplugin.cpp +++ b/src/corelib/doc/snippets/code/doc_src_qplugin.cpp @@ -22,9 +22,3 @@ class MyInstance : public QObject //! [2] Q_IMPORT_PLUGIN(qjpeg) //! [2] - - -//! [3] -TEMPLATE = app -QTPLUGIN += qjpeg qgif # image formats -//! [3] diff --git a/src/corelib/doc/snippets/code/doc_src_qset.cpp b/src/corelib/doc/snippets/code/doc_src_qset.cpp index 64e0b6e450..98a6f336f5 100644 --- a/src/corelib/doc/snippets/code/doc_src_qset.cpp +++ b/src/corelib/doc/snippets/code/doc_src_qset.cpp @@ -34,18 +34,15 @@ while (i.hasNext()) { //! [5] -QSet<QWidget *>::const_iterator i = set.constBegin(); -while (i != set.constEnd()) { +for (auto i = set.cbegin(), end = set.cend(); i != end; ++i) qDebug() << *i; - ++i; -} //! [5] //! [6] QSet<QString> set; ... -foreach (const QString &value, set) +for (const auto &value : set) qDebug() << value; //! [6] @@ -59,20 +56,18 @@ for (int i = 0; i < 20000; ++i) //! [8] -QSet<QString> set; -set << "January" << "February" << ... << "December"; +QSet<QString> set = {"January", "February", ... "December"} -QSet<QString>::iterator i; -for (i = set.begin(); i != set.end(); ++i) +// i is a QSet<QString>::iterator +for (auto i = set.begin(), end = set.end(); i != end; ++i) qDebug() << *i; //! [8] //! [9] -QSet<QString> set; -set << "January" << "February" << ... << "December"; +QSet<QString> set = {"January", "February", ... "December"}; -QSet<QString>::iterator i = set.begin(); +auto i = set.begin(); while (i != set.end()) { if ((*i).startsWith('J')) { i = set.erase(i); @@ -94,11 +89,10 @@ if (it != set.end()) //! [11] -QSet<QString> set; -set << "January" << "February" << ... << "December"; +QSet<QString> set = {"January", "February", ... "December"}; -QSet<QString>::const_iterator i; -for (i = set.begin(); i != set.end(); ++i) +// i is QSet<QString>::const_iterator +for (auto i = set.cbegin(), end = set.cend(); i != end; ++i) qDebug() << *i; //! [11] @@ -111,23 +105,3 @@ QSet<QString>::const_iterator it = std::find_if(set.cbegin(), set.cend(), predic if (it != set.constEnd()) cout << "Found Jeanette" << endl; //! [12] - - -//! [13] -QSet<QString> set; -set << "red" << "green" << "blue" << ... << "black"; - -QList<QString> list = set.toList(); -std::sort(list.begin(), list.end()); -//! [13] - - -//! [14] -QStringList list; -list << "Julia" << "Mike" << "Mike" << "Julia" << "Julia"; - -QSet<QString> set = QSet<QString>::fromList(list); -set.contains("Julia"); // returns true -set.contains("Mike"); // returns true -set.size(); // returns 2 -//! [14] diff --git a/src/corelib/doc/snippets/code/doc_src_resources.cpp b/src/corelib/doc/snippets/code/doc_src_resources.cpp index 5df085d145..04ecf810ec 100644 --- a/src/corelib/doc/snippets/code/doc_src_resources.cpp +++ b/src/corelib/doc/snippets/code/doc_src_resources.cpp @@ -15,16 +15,3 @@ MyClass::MyClass() : BaseClass() ... } //! [5] - - -//! [6] -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - Q_INIT_RESOURCE(graphlib); - - QFile file(":/graph.png"); - ... - return app.exec(); -} -//! [6] diff --git a/src/corelib/doc/snippets/code/doc_src_resources.qdoc b/src/corelib/doc/snippets/code/doc_src_resources.qdoc index a2e515ce03..70c2a7b7ab 100644 --- a/src/corelib/doc/snippets/code/doc_src_resources.qdoc +++ b/src/corelib/doc/snippets/code/doc_src_resources.qdoc @@ -1,5 +1,5 @@ // Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only //! [0] <file alias="cut-img.png">images/cut.png</file> @@ -26,3 +26,7 @@ //! [3] rcc -binary myresource.qrc -o myresource.rcc //! [3] + +//! [4] +<file empty="true">Button.qml</file> +//! [4] diff --git a/src/corelib/doc/snippets/code/qlogging/qlogging.cpp b/src/corelib/doc/snippets/code/qlogging/qlogging.cpp index d1c3c7b00d..e61eb70df3 100644 --- a/src/corelib/doc/snippets/code/qlogging/qlogging.cpp +++ b/src/corelib/doc/snippets/code/qlogging/qlogging.cpp @@ -1,14 +1,16 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +#undef QT_NO_FOREACH // this file contains unported legacy Q_FOREACH uses + #include <QtGui> #include <QtDebug> -#include <QDeclarativeComponent> +#include <QQmlComponent> //! [1] - void statusChanged(QDeclarativeComponent::Status status) { - if (status == QDeclarativeComponent::Error) { - foreach (const QDeclarativeError &error, component->errors()) { + void statusChanged(QQmlComponent::Status status) { + if (status == QQmlComponent::Error) { + for (const QQmlError &error: std::as_const(component->errors())) { const QByteArray file = error.url().toEncoded(); QMessageLogger(file.constData(), error.line(), 0).debug() << error.description(); } diff --git a/src/corelib/doc/snippets/code/src_corelib_animation_qpropertyanimation.cpp b/src/corelib/doc/snippets/code/src_corelib_animation_qpropertyanimation.cpp index f8b74cd542..4b77ab607d 100644 --- a/src/corelib/doc/snippets/code/src_corelib_animation_qpropertyanimation.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_animation_qpropertyanimation.cpp @@ -6,7 +6,7 @@ #include <QApplication> #include <QPushButton> #include <QPropertyAnimation> -//! [1] + class MyButtonWidget : public QWidget { public: @@ -31,7 +31,6 @@ int main(int argc, char *argv[]) buttonAnimWidget.show(); return a.exec(); } -//! [1] //! [0] diff --git a/src/corelib/doc/snippets/code/src_corelib_global_qglobal.cpp b/src/corelib/doc/snippets/code/src_corelib_global_qglobal.cpp index 4d6f566bf8..25d3abf67e 100644 --- a/src/corelib/doc/snippets/code/src_corelib_global_qglobal.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_global_qglobal.cpp @@ -32,17 +32,6 @@ Q_FLAG(Options) typedef QFlags<Enum> Flags; //! [2] - -//! [3] -int myValue = 10; -int minValue = 2; -int maxValue = 6; - -int boundedValue = qBound(minValue, myValue, maxValue); -// boundedValue == 6 -//! [3] - - //! [4] if (!driver()->isOpen() || driver()->isOpenError()) { qWarning("QSqlQuery::exec: database not open"); @@ -61,11 +50,6 @@ quint64 value = Q_UINT64_C(932838457459459); //! [6] -//! [7] -void myMsgHandler(QtMsgType, const char *); -//! [7] - - //! [8] qint64 value = Q_INT64_C(932838457459459); //! [8] @@ -226,37 +210,26 @@ const TInputType &myMin(const TInputType &value1, const TInputType &value2) //! [23] -#include <qapplication.h> +#include <QApplication> #include <stdio.h> #include <stdlib.h> -void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) +QtMessageHandler originalHandler = nullptr; + +void logToFile(QtMsgType type, const QMessageLogContext &context, const QString &msg) { - QByteArray localMsg = msg.toLocal8Bit(); - const char *file = context.file ? context.file : ""; - const char *function = context.function ? context.function : ""; - switch (type) { - case QtDebugMsg: - fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); - break; - case QtInfoMsg: - fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); - break; - case QtWarningMsg: - fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); - break; - case QtCriticalMsg: - fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); - break; - case QtFatalMsg: - fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); - break; - } + QString message = qFormatLogMessage(type, context, msg); + static FILE *f = fopen("log.txt", "a"); + fprintf(f, "%s\n", qPrintable(message)); + fflush(f); + + if (originalHandler) + *originalHandler(type, context, msg); } int main(int argc, char **argv) { - qInstallMessageHandler(myMessageOutput); + originalHandler = qInstallMessageHandler(logToFile); QApplication app(argc, argv); ... return app.exec(); @@ -579,11 +552,6 @@ qFuzzyCompare(0.0, 1.0e-200); // This will return false qFuzzyCompare(1 + 0.0, 1 + 1.0e-200); // This will return true //! [46] -//! [47] -CApaApplication *myApplicationFactory(); -//! [47] - - //! [49] void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &); //! [49] diff --git a/src/corelib/doc/snippets/code/src_corelib_io_qabstractfileengine.cpp b/src/corelib/doc/snippets/code/src_corelib_io_qabstractfileengine.cpp index 8c80ec1eba..4300fc2da9 100644 --- a/src/corelib/doc/snippets/code/src_corelib_io_qabstractfileengine.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_io_qabstractfileengine.cpp @@ -1,17 +1,21 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +using namespace Qt::StringLiterals; + //! [0] class ZipEngineHandler : public QAbstractFileEngineHandler { public: - QAbstractFileEngine *create(const QString &fileName) const override; + std::unique_ptr<QAbstractFileEngine> create(const QString &fileName) const override; }; -QAbstractFileEngine *ZipEngineHandler::create(const QString &fileName) const +std::unique_ptr<QAbstractFileEngine> ZipEngineHandler::create(const QString &fileName) const { // ZipEngineHandler returns a ZipEngine for all .zip files - return fileName.toLower().endsWith(".zip") ? new ZipEngine(fileName) : 0; + if (fileName.toLower().endsWith(".zip"_L1)) + return std::make_unique<ZipEngine>(fileName); + return {}; } int main(int argc, char **argv) @@ -27,21 +31,24 @@ int main(int argc, char **argv) } //! [0] - //! [1] -QAbstractSocketEngine *ZipEngineHandler::create(const QString &fileName) const +std::unique_ptr<QAbstractFileEngine> ZipEngineHandler::create(const QString &fileName) const { // ZipEngineHandler returns a ZipEngine for all .zip files - return fileName.toLower().endsWith(".zip") ? new ZipEngine(fileName) : 0; + if (fileName.toLower().endsWith(".zip"_L1)) + return std::make_unique<ZipEngine>(fileName); + else + return {}; } //! [1] //! [2] -QAbstractFileEngineIterator * -CustomFileEngine::beginEntryList(QDir::Filters filters, const QStringList &filterNames) +QAbstractFileEngine::IteratorUniquePtr +CustomFileEngine::beginEntryList(const QString &path, QDir::Filters filters, + const QStringList &filterNames) { - return new CustomFileEngineIterator(filters, filterNames); + return std::make_unique<CustomFileEngineIterator>(path, filters, filterNames); } //! [2] @@ -50,25 +57,23 @@ CustomFileEngine::beginEntryList(QDir::Filters filters, const QStringList &filte class CustomIterator : public QAbstractFileEngineIterator { public: - CustomIterator(const QStringList &nameFilters, QDir::Filters filters) - : QAbstractFileEngineIterator(nameFilters, filters), index(0) + CustomIterator(const QString &path, const QStringList &nameFilters, QDir::Filters filters) + : QAbstractFileEngineIterator(path, nameFilters, filters), index(0) { // In a real iterator, these entries are fetched from the // file system based on the value of path(). entries << "entry1" << "entry2" << "entry3"; } - bool hasNext() const override - { - return index < entries.size() - 1; - } - - QString next() override + bool advance() override { - if (!hasNext()) - return QString(); - ++index; - return currentFilePath(); + if (entries.isEmpty()) + return false; + if (index < entries.size() - 1) { + ++index; + return true; + } + return false; } QString currentFileName() override diff --git a/src/corelib/doc/snippets/code/src_corelib_io_qdirlisting.cpp b/src/corelib/doc/snippets/code/src_corelib_io_qdirlisting.cpp new file mode 100644 index 0000000000..231bf48d26 --- /dev/null +++ b/src/corelib/doc/snippets/code/src_corelib_io_qdirlisting.cpp @@ -0,0 +1,70 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#include <QDirListing> + +using namespace Qt::StringLiterals; + +[[maybe_unused]] static void func() { +{ +//! [0] +using ItFlag = QDirListing::IteratorFlag; +for (const auto &dirEntry : QDirListing(u"/etc"_s, ItFlag::Recursive)) { + qDebug() << dirEntry.filePath(); + // /etc/. + // /etc/.. + // /etc/X11 + // /etc/X11/fs + // ... +} +//! [0] +} + +{ +//! [1] +using ItFlag = QDirListing::IteratorFlag; +QDirListing dirList(u"/sys"_s, QStringList{u"scaling_cur_freq"_s}, + QDir::NoFilter, ItFlag::Recursive); +for (const auto &dirEntry : dirList) { + QFile f(dirEntry.filePath()); + f.open(QIODevice::ReadOnly); + qDebug() << f.fileName() << f.readAll().trimmed().toDouble() / 1000 << "MHz"; +} +//! [1] +} + +{ +//! [2] +QDirListing audioFileIt(u"/home/johndoe/"_s, {"*.mp3", "*.wav"}, QDir::Files); +//! [2] +} + +{ +//! [3] +using ItFlag = QDirListing::IteratorFlag; +for (const auto &dirEntry : QDirListing(u"/etc"_s, ItFlag::Recursive)) { + // Faster + if (dirEntry.fileName().endsWith(u".conf")) { /* ... */ } + + // This works, but might be potentially slower, since it has to construct a + // QFileInfo, whereas (depending on the implemnetation) the fileName could + // be known already + if (dirEntry.fileInfo().fileName().endsWith(u".conf")) { /* ... */ } +} +//! [3] +} + +{ +//! [4] +using ItFlag = QDirListing::IteratorFlag; +for (const auto &dirEntry : QDirListing(u"/etc"_s, ItFlag::Recursive)) { + // Both approaches are the same, because DirEntry will have to construct + // a QFileInfo to get this info (for example, by calling system stat()) + + if (dirEntry.size() >= 4'000 /* 4KB */) { /* ...*/ } + if (dirEntry.fileInfo().size() >= 4'000 /* 4KB */) { /* ... */ } +} +//! [4] +} + +} diff --git a/src/corelib/doc/snippets/code/src_corelib_io_qfile.cpp b/src/corelib/doc/snippets/code/src_corelib_io_qfile.cpp index 475bc874ec..3a8f7d2747 100644 --- a/src/corelib/doc/snippets/code/src_corelib_io_qfile.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_io_qfile.cpp @@ -10,16 +10,6 @@ file.open(QIODevice::ReadOnly); // opens "/home/readme.txt" under Unix //! [0] -//! [1] -QByteArray myEncoderFunc(const QString &fileName); -//! [1] - - -//! [2] -QString myDecoderFunc(const QByteArray &localFileName); -//! [2] - - //! [3] #include <stdio.h> diff --git a/src/corelib/doc/snippets/code/src_corelib_io_qfileinfo.cpp b/src/corelib/doc/snippets/code/src_corelib_io_qfileinfo.cpp index 9e548afafc..a8dd621111 100644 --- a/src/corelib/doc/snippets/code/src_corelib_io_qfileinfo.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_io_qfileinfo.cpp @@ -1,11 +1,21 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +#include <QDir> +#include <QFileInfo> +using namespace Qt::StringLiterals; + +[[maybe_unused]] static void func() +{ +{ //![newstuff] - QFileInfo fi("c:/temp/foo"); => fi.absoluteFilePath() => "C:/temp/foo" + QFileInfo fi("c:/temp/foo"); + qDebug() << fi.absoluteFilePath(); // "C:/temp/foo" //![newstuff] +} +{ //! [0] #ifdef Q_OS_UNIX @@ -22,7 +32,7 @@ info2.size(); // returns 56201 #endif //! [0] - +} //! [1] #ifdef Q_OS_WIN @@ -41,7 +51,7 @@ info2.size(); // returns 63942 #endif //! [1] - +{ //! [2] QFileInfo info("/usr/bin/env"); @@ -53,50 +63,60 @@ info.setFile("/etc/hosts"); path = info.absolutePath(); // path = /etc base = info.baseName(); // base = hosts //! [2] +} +{ //! [3] QFileInfo fi("/tmp/archive.tar.gz"); QString name = fi.fileName(); // name = "archive.tar.gz" //! [3] +} - +{ //! [4] QFileInfo fi("/Applications/Safari.app"); QString bundle = fi.bundleName(); // name = "Safari" //! [4] +} - +{ //! [5] QFileInfo fi("/tmp/archive.tar.gz"); QString base = fi.baseName(); // base = "archive" //! [5] +} - +{ //! [6] QFileInfo fi("/tmp/archive.tar.gz"); QString base = fi.completeBaseName(); // base = "archive.tar" //! [6] +} - +{ //! [7] QFileInfo fi("/tmp/archive.tar.gz"); QString ext = fi.completeSuffix(); // ext = "tar.gz" //! [7] +} - +{ //! [8] QFileInfo fi("/tmp/archive.tar.gz"); QString ext = fi.suffix(); // ext = "gz" //! [8] +} - +{ +QString fileName = "foo"; //! [9] QFileInfo info(fileName); if (info.isSymLink()) fileName = info.symLinkTarget(); //! [9] +} - +{ //! [10] QFileInfo fi("/tmp/archive.tar.gz"); if (fi.permission(QFile::WriteUser | QFile::ReadGroup)) @@ -104,3 +124,24 @@ if (fi.permission(QFile::WriteUser | QFile::ReadGroup)) if (fi.permission(QFile::WriteGroup | QFile::WriteOther)) qWarning("The group or others can change the file"); //! [10] +} + +{ +//! [11] +// Given a current working directory of "/home/user/Documents/memos/" +QFileInfo info1(u"relativeFile"_s); +qDebug() << info1.absolutePath(); // "/home/user/Documents/memos/" +qDebug() << info1.baseName(); // "relativeFile" +qDebug() << info1.absoluteDir(); // QDir(u"/home/user/Documents/memos"_s) +qDebug() << info1.absoluteDir().path(); // "/home/user/Documents/memos" + +// A QFileInfo on a dir +QFileInfo info2(u"/home/user/Documents/memos"_s); +qDebug() << info2.absolutePath(); // "/home/user/Documents" +qDebug() << info2.baseName(); // "memos" +qDebug() << info2.absoluteDir(); // QDir(u"/home/user/Documents"_s) +qDebug() << info2.absoluteDir().path(); // "/home/user/Documents" +//! [11] +} + +} diff --git a/src/corelib/doc/snippets/code/src_corelib_io_qsettings.cpp b/src/corelib/doc/snippets/code/src_corelib_io_qsettings.cpp index cc93e32d05..5774add2a7 100644 --- a/src/corelib/doc/snippets/code/src_corelib_io_qsettings.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_io_qsettings.cpp @@ -45,7 +45,7 @@ settings.value("HKEY_CURRENT_USER\\MySoft\\Star Runner\\Galaxy\\Default"); // re //! [7] -#ifdef Q_OS_MAC +#ifdef Q_OS_DARWIN QSettings settings("grenoullelogique.fr", "Squash"); #else QSettings settings("Grenoulle Logique", "Squash"); @@ -138,10 +138,10 @@ QList<Login> logins; QSettings settings; settings.beginWriteArray("logins"); -for (int i = 0; i < logins.size(); ++i) { +for (qsizetype i = 0; i < logins.size(); ++i) { settings.setArrayIndex(i); - settings.setValue("userName", list.at(i).userName); - settings.setValue("password", list.at(i).password); + settings.setValue("userName", logins.at(i).userName); + settings.setValue("password", logins.at(i).password); } settings.endArray(); //! [16] diff --git a/src/corelib/doc/snippets/code/src_corelib_io_qstorageinfo.cpp b/src/corelib/doc/snippets/code/src_corelib_io_qstorageinfo.cpp index d11368a83d..93029274b1 100644 --- a/src/corelib/doc/snippets/code/src_corelib_io_qstorageinfo.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_io_qstorageinfo.cpp @@ -1,6 +1,8 @@ // Copyright (C) 2014 Ivan Komissarov // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +#undef QT_NO_FOREACH // this file contains unported legacy Q_FOREACH uses + //! [0] QStorageInfo storage(qApp->applicationDirPath()); if (storage.isValid() && storage.isReady()) { diff --git a/src/corelib/doc/snippets/code/src_corelib_io_qtextstream.cpp b/src/corelib/doc/snippets/code/src_corelib_io_qtextstream.cpp index bcc08c0f16..75a04e654f 100644 --- a/src/corelib/doc/snippets/code/src_corelib_io_qtextstream.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_io_qtextstream.cpp @@ -84,9 +84,3 @@ out << "Qt rocks!" << Qt::endl; //! [9] stream << '\n' << Qt::flush; //! [9] - - -//! [10] -QTextStream out(&file); -out.setEncoding(QStringConverter::Utf8); -//! [10] diff --git a/src/corelib/doc/snippets/code/src_corelib_io_qurl.cpp b/src/corelib/doc/snippets/code/src_corelib_io_qurl.cpp index 62ecc58a80..945f3ae3e7 100644 --- a/src/corelib/doc/snippets/code/src_corelib_io_qurl.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_io_qurl.cpp @@ -1,6 +1,14 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +//! [constructor-url-reference] +QUrl url("example.com"); +//! [constructor-url-reference] + +//! [constructor-url] +QUrl url("https://example.com"); +//! [constructor-url] + //! [0] QUrl url("http://www.example.com/List of holidays.xml"); // url.toEncoded() == "http://www.example.com/List%20of%20holidays.xml" @@ -31,7 +39,7 @@ sock.connectToHost(url.host(), url.port(80)); //! [4] -http://www.example.com/cgi-bin/drawgraph.cgi?type(pie)color(green) +http://www.example.com/cgi-bin/drawgraph.cgi?type,pie;color,green //! [4] diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qabstractitemmodel.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qabstractitemmodel.cpp index 3f7dc07d9f..4fd7f97ae8 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qabstractitemmodel.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qabstractitemmodel.cpp @@ -50,16 +50,6 @@ beginMoveRows(parent, 2, 2, parent, 0); beginMoveRows(parent, 2, 2, parent, 4); //! [9] -//! [10] -myData.clear(); -reset(); -//! [10] - -//! [11] -beginResetModel(); -myData.clear(); -endResetModel(); -//! [11] //! [12] class CustomDataProxy : public QSortFilterProxyModel diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qcoreapplication.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qcoreapplication.cpp index 2a3a27e94b..8087ff8f8b 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qcoreapplication.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qcoreapplication.cpp @@ -1,6 +1,8 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +#undef QT_NO_FOREACH // this file contains unported legacy Q_FOREACH uses + //! [0] QMouseEvent event(QEvent::MouseButtonPress, pos, 0, 0, 0); QApplication::sendEvent(mainWindow, &event); @@ -13,12 +15,6 @@ connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::Qu //! [1] -//! [2] -foreach (const QString &path, app.libraryPaths()) - do_something(path); -//! [2] - - //! [3] // Called once QCoreApplication exists static void preRoutineMyDebugTool() diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qdeadlinetimer.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qdeadlinetimer.cpp index a3b366a588..f7440f2bb0 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qdeadlinetimer.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qdeadlinetimer.cpp @@ -63,25 +63,25 @@ //! [7] //! [8] - return d1.deadlineNSecs() == d2.deadlineNSecs(); + return lhs.deadlineNSecs() == rhs.deadlineNSecs(); //! [8] //! [9] - return d1.deadlineNSecs() != d2.deadlineNSecs(); + return lhs.deadlineNSecs() != rhs.deadlineNSecs(); //! [9] //! [10] - return d1.deadlineNSecs() < d2.deadlineNSecs(); + return lhs.deadlineNSecs() < rhs.deadlineNSecs(); //! [10] //! [11] - return d1.deadlineNSecs() <= d2.deadlineNSecs(); + return lhs.deadlineNSecs() <= rhs.deadlineNSecs(); //! [11] //! [12] - return d1.deadlineNSecs() > d2.deadlineNSecs(); + return lhs.deadlineNSecs() > rhs.deadlineNSecs(); //! [12] //! [13] - return d1.deadlineNSecs() >= d2.deadlineNSecs(); + return lhs.deadlineNSecs() >= rhs.deadlineNSecs(); //! [13] diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qmetatype.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qmetatype.cpp index a213ccbca6..757700786e 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qmetatype.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qmetatype.cpp @@ -101,16 +101,6 @@ void someFunc() //! [11] -//! [12] -QPointer<QFile> fp(new QFile); -QVariant var = QVariant::fromValue(fp); -// ... -if (var.canConvert<QObject*>()) { - QObject *sp = var.value<QObject*>(); - qDebug() << sp->metaObject()->className(); // Prints 'QFile'. -} -//! [12] - //! [13] #include <memory> diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qmimedata.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qmimedata.cpp index 36cbdefa1c..c6a48c8827 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qmimedata.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qmimedata.cpp @@ -1,6 +1,8 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +#undef QT_NO_FOREACH // this file contains unported legacy Q_FOREACH uses + //! [0] void MyWidget::dragEnterEvent(QDragEnterEvent *event) { diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qobject.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qobject.cpp index 2c5483abce..e3bbac7a3c 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qobject.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qobject.cpp @@ -129,13 +129,6 @@ void MyObject::timerEvent(QTimerEvent *event) //! [8] -//! [9] -QList<QObject *> list = window()->queryList("QAbstractButton")); -foreach (QObject *obj, list) - static_cast<QAbstractButton *>(obj)->setEnabled(false); -//! [9] - - //! [10] QPushButton *button = parentWidget->findChild<QPushButton *>("button1"); //! [10] @@ -204,22 +197,6 @@ MyWindow::MyWindow() } -//! [18] -int n = messages.count(); -showMessage(tr("%n message(s) saved", "", n)); -//! [18] - - -//! [19] -n == 1 ? tr("%n message saved") : tr("%n messages saved") -//! [19] - - -//! [20] -label->setText(tr("F\374r \310lise")); -//! [20] - - //! [21] if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) { QByteArray data; @@ -383,21 +360,13 @@ public: //! [39] -//! [40] -//: This name refers to a host name. -hostNameLabel->setText(tr("Name:")); - -/*: This text refers to a C++ code example. */ -QString example = tr("Example"); -//! [40] - //! [41] QPushButton *button = parentWidget->findChild<QPushButton *>("button1", Qt::FindDirectChildrenOnly); //! [41] //! [42] -QListWidget *list = parentWidget->findChild<QListWidget *>(QString(), Qt::FindDirectChildrenOnly); +QListWidget *list = parentWidget->findChild<QListWidget *>(Qt::FindDirectChildrenOnly); //! [42] @@ -487,18 +456,6 @@ public: }; //! [52] -//! [meta data] -//: This is a comment for the translator. -//= qtn_foo_bar -//~ loc-layout_id foo_dialog -//~ loc-blank False -//~ magic-stuff This might mean something magic. -QString text = MyMagicClass::tr("Sim sala bim."); -//! [meta data] - -//! [explicit tr context] -QString text = QScrollBar::tr("Page up"); -//! [explicit tr context] //! [53] { @@ -512,3 +469,16 @@ const bool wasBlocked = someQObject->blockSignals(true); // no signals here someQObject->blockSignals(wasBlocked); //! [54] + +{ +//! [invalid-timer-id] + QObject *obj; + ... + int id = obj->startTimer(100ms); + if (id > Qt::TimerId::Invalid) + // The timer has been started successfully + + if (id > 0) // Equivalent, albeit less readable + // The timer has been started successfully +//! [invalid-timer-id] +} diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qproperty.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qproperty.cpp index f4cc826e6f..c2b55c9684 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qproperty.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qproperty.cpp @@ -144,7 +144,7 @@ public: Q_D(MyClass); d->clients.push_back(c); // notify that the value could have changed - d->hasClientsData.markDirty(); + d->hasClientsData.notify(); } private: Q_DECLARE_PRIVATE(MyClass) diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qsystemsemaphore.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qsystemsemaphore.cpp index d1afba270e..45da88c75d 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qsystemsemaphore.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qsystemsemaphore.cpp @@ -2,7 +2,7 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause //! [0] -QSystemSemaphore sem("market", 3, QSystemSemaphore::Create); +QSystemSemaphore sem(QSystemSemaphore::platformSafeKey("market"), 3, QSystemSemaphore::Create); // resources available == 3 sem.acquire(); // resources available == 2 sem.acquire(); // resources available == 1 @@ -13,7 +13,7 @@ sem.release(2); // resources available == 3 //! [1] -QSystemSemaphore sem("market", 5, QSystemSemaphore::Create); +QSystemSemaphore sem(QSystemSemaphore::platformSafeKey("market"), 5, QSystemSemaphore::Create); for (int i = 0; i < 5; ++i) // acquire all 5 resources sem.acquire(); sem.release(5); // release the 5 resources diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qtimer.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qtimer.cpp index 7dfd17a1f1..5edcaae755 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qtimer.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qtimer.cpp @@ -8,7 +8,7 @@ int main(int argc, char *argv[]) { QApplication app(argc, argv); - QTimer::singleShot(600000, &app, SLOT(quit())); + QTimer::singleShot(600000, &app, QCoreApplication::quit); ... return app.exec(); } diff --git a/src/corelib/doc/snippets/code/src_corelib_kernel_qvariant.cpp b/src/corelib/doc/snippets/code/src_corelib_kernel_qvariant.cpp index e0c846a587..7f3f1ce7a0 100644 --- a/src/corelib/doc/snippets/code/src_corelib_kernel_qvariant.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_kernel_qvariant.cpp @@ -1,6 +1,8 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +#undef QT_NO_FOREACH // this file contains unported legacy Q_FOREACH uses + //! [0] QDataStream out(...); QVariant v(123); // The variant now contains an int @@ -89,11 +91,6 @@ return QVariant::fromValue(s); //! [7] -//! [8] -QObject *object = getObjectFromSomewhere(); -QVariant data = QVariant::fromValue(object); -//! [8] - //! [9] QList<int> intList = {7, 11, 42}; diff --git a/src/corelib/doc/snippets/code/src_corelib_serialization_qcborstream.cpp b/src/corelib/doc/snippets/code/src_corelib_serialization_qcborstream.cpp index 90f89d8bd1..acb5a6272e 100644 --- a/src/corelib/doc/snippets/code/src_corelib_serialization_qcborstream.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_serialization_qcborstream.cpp @@ -183,7 +183,7 @@ using namespace Qt::StringLiterals; //! [21] //! [22] - void appendMap(QCborStreamWriter &writer, const QList<QPair<int, QString>> &values) + void appendMap(QCborStreamWriter &writer, const QList<std::pair<int, QString>> &values) { writer.startMap(); for (const auto pair : values) { @@ -198,7 +198,7 @@ using namespace Qt::StringLiterals; void appendMap(QCborStreamWriter &writer, const QMap<int, QString> &map) { writer.startMap(map.size()); - for (auto it = map.begin(); it != map.end(); ++it) { + for (auto it = map.cbegin(), end = map.cend(); it != end; ++it) { writer.append(it.key()); writer.append(it.value()); } @@ -271,12 +271,12 @@ using namespace Qt::StringLiterals; { QString result; auto r = reader.readString(); - while (r.code == QCborStreamReader::Ok) { + while (r.status == QCborStreamReader::Ok) { result += r.data; r = reader.readString(); } - if (r.code == QCborStreamReader::Error) { + if (r.status == QCborStreamReader::Error) { // handle error condition result.clear(); } @@ -289,12 +289,12 @@ using namespace Qt::StringLiterals; { QBytearray result; auto r = reader.readBytearray(); - while (r.code == QCborStreamReader::Ok) { + while (r.status == QCborStreamReader::Ok) { result += r.data; r = reader.readByteArray(); } - if (r.code == QCborStreamReader::Error) { + if (r.status == QCborStreamReader::Error) { // handle error condition result.clear(); } diff --git a/src/corelib/doc/snippets/code/src_corelib_serialization_qdatastream.cpp b/src/corelib/doc/snippets/code/src_corelib_serialization_qdatastream.cpp index 296a341b11..dfdebe6a76 100644 --- a/src/corelib/doc/snippets/code/src_corelib_serialization_qdatastream.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_serialization_qdatastream.cpp @@ -2,11 +2,11 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause //! [0] - QDataStream &operator<<(QDataStream &, const QXxx &); - QDataStream &operator>>(QDataStream &, QXxx &); +QDataStream &operator<<(QDataStream &, const QXxx &); +QDataStream &operator>>(QDataStream &, QXxx &); //! [0] //! [1] - QDataStream & operator<< (QDataStream& stream, const QImage& image); - QDataStream & operator>> (QDataStream& stream, QImage& image); +QDataStream &operator<<(QDataStream &stream, const QImage &image); +QDataStream &operator>>(QDataStream &stream, QImage &image); //! [1] diff --git a/src/corelib/doc/snippets/code/src_corelib_text_qbytearray.cpp b/src/corelib/doc/snippets/code/src_corelib_text_qbytearray.cpp index 8a9cb7c841..a4fecc41f9 100644 --- a/src/corelib/doc/snippets/code/src_corelib_text_qbytearray.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_text_qbytearray.cpp @@ -24,7 +24,7 @@ ba[4] = 0xca; //! [2] for (qsizetype i = 0; i < ba.size(); ++i) { if (ba.at(i) >= 'a' && ba.at(i) <= 'f') - cout << "Found character in range [a-f]" << Qt::endl; + cout << "Found character in range [a-f]" << endl; } //! [2] @@ -41,7 +41,7 @@ x.replace(5, 3, "&"); // x == "rock & roll" QByteArray ba("We must be <b>bold</b>, very <b>bold</b>"); qsizetype j = 0; while ((j = ba.indexOf("<b>", j)) != -1) { - cout << "Found <b> tag at index position " << j << Qt::endl; + cout << "Found <b> tag at index position " << j << endl; ++j; } //! [4] @@ -79,7 +79,7 @@ QByteArray("abc").isEmpty(); // returns false QByteArray ba("Hello world"); char *data = ba.data(); while (*data) { - cout << "[" << *data << "]" << Qt::endl; + cout << "[" << *data << "]" << endl; ++data; } //! [8] @@ -461,4 +461,21 @@ QByteArray ba = QByteArrayLiteral("byte array contents"); QByteArray encoded("Qt%20is%20great%33"); QByteArray decoded = encoded.percentDecoded(); // Set to "Qt is great!" //! [54] + +//! [55] +emscripten::val uint8array = emscripten::val::global("g_uint8array"); +QByteArray byteArray = QByteArray::fromEcmaUint8Array(uint8array); +//! [55] + +//! [56] +QByteArray byteArray = "test"; +emscripten::val uint8array = QByteArray::toEcmaUint8Array(byteArray); +//! [56] + +//! [57] +QByteArray x = "Five pineapples"_ba; +x.slice(5); // x == "pineapples" +x.slice(4, 3); // x == "app" +//! [57] + } diff --git a/src/corelib/doc/snippets/code/src_corelib_text_qstaticlatin1stringmatcher.cpp b/src/corelib/doc/snippets/code/src_corelib_text_qstaticlatin1stringmatcher.cpp new file mode 100644 index 0000000000..ae6e19e471 --- /dev/null +++ b/src/corelib/doc/snippets/code/src_corelib_text_qstaticlatin1stringmatcher.cpp @@ -0,0 +1,8 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +//! [0] +static constexpr auto matcher = qMakeStaticCaseSensitiveLatin1StringViewMatcher("needle"); +//! [0] +//! [1] +static constexpr auto matcher = qMakeStaticCaseInsensitiveLatin1StringViewMatcher("needle"); +//! [1] diff --git a/src/corelib/doc/snippets/code/src_corelib_text_qstring.cpp b/src/corelib/doc/snippets/code/src_corelib_text_qstring.cpp index 2c195fd24f..efb529657a 100644 --- a/src/corelib/doc/snippets/code/src_corelib_text_qstring.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_text_qstring.cpp @@ -30,6 +30,9 @@ if (str == QString("auto") || str == QString("extern") } //! [4] +//! [4bis] +str.append("Hello ").append("World"); +//! [4bis] //! [5] if (str == "auto"_L1 diff --git a/src/corelib/doc/snippets/code/src_corelib_text_qstringconverter.cpp b/src/corelib/doc/snippets/code/src_corelib_text_qstringconverter.cpp index e7bd39c95c..b5bfc9cd55 100644 --- a/src/corelib/doc/snippets/code/src_corelib_text_qstringconverter.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_text_qstringconverter.cpp @@ -34,3 +34,27 @@ while (new_data_available()) { encoded += fromUtf16(chunk); } //! [3] + +{ +//! [4] +QByteArray encodedString = "..."; +auto toUtf16 = QStringDecoder(QStringDecoder::Utf8); +auto data = toUtf16(encodedString); // data's type is QStringDecoder::EncodedData<const QByteArray &> +QString string = toUtf16(encodedString); // Implicit conversion to QString + +// Here you have to cast "data" to QString +auto func = [&]() { return !toUtf16.hasError() ? QString(data) : u"foo"_s; } +//! [4] +} + +{ +//! [5] +QString string = "..."; +auto fromUtf16 = QStringEncoder(QStringEncoder::Utf8); +auto data = fromUtf16(string); // data's type is QStringEncoder::DecodedData<const QString &> +QByteArray encodedString = fromUtf16(string); // Implicit conversion to QByteArray + +// Here you have to cast "data" to QByteArray +auto func = [&]() { return !fromUtf16.hasError() ? QByteArray(data) : "foo"_ba; } +//! [5] +} diff --git a/src/corelib/doc/snippets/code/src_corelib_thread_qfuture.cpp b/src/corelib/doc/snippets/code/src_corelib_thread_qfuture.cpp index 091d98539b..500d7cc7a5 100644 --- a/src/corelib/doc/snippets/code/src_corelib_thread_qfuture.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_thread_qfuture.cpp @@ -6,7 +6,7 @@ QFuture<QString> future = ...; QFuture<QString>::const_iterator i; for (i = future.constBegin(); i != future.constEnd(); ++i) - cout << *i << Qt::endl; + cout << qPrintable(*i) << endl; //! [0] @@ -239,9 +239,9 @@ auto future = QtConcurrent::run([] { //! [20] QObject *context = ...; -auto future = cachedResultsReady ? QtFuture::makeReadyFuture(results) - : QtConcurrent::run([] { /* compute results */}); -auto continuation = future.then(context, [] (Results results) { +auto future = cachedResultsReady ? QtFuture::makeReadyValueFuture(result) + : QtConcurrent::run([] { /* compute result */}); +auto continuation = future.then(context, [] (Result result) { // Runs in the context's thread }).then([] { // May or may not run in the context's thread @@ -385,3 +385,58 @@ QFuture<QFuture<QFuture<int>>>> outerFuture; QFuture<int> unwrappedFuture = outerFuture.unwrap(); //! [30] + +//! [31] +QPromise<int> p; + +QFuture<int> f1 = p.future(); +f1.then([](int) { qDebug("first"); }); + +QFuture<int> f2 = p.future(); +f2.then([](int) { qDebug("second"); }); + +p.start(); +p.addResult(42); +p.finish(); +//! [31] + +//! [32] +const std::vector<int> values{1, 2, 3}; +auto f = QtFuture::makeReadyRangeFuture(values); +//! [32] + +//! [33] +auto f = QtFuture::makeReadyRangeFuture({1, 2, 3}); +//! [33] + +//! [34] +const int count = f.resultCount(); // count == 3 +const auto results = f.results(); // results == { 1, 2, 3 } +//! [34] + +//! [35] +auto f = QtFuture::makeReadyValueFuture(std::make_unique<int>(42)); +... +const int result = *f.takeResult(); // result == 42 +//! [35] + +//! [36] +auto f = QtFuture::makeReadyVoidFuture(); +... +const bool started = f.isStarted(); // started == true +const bool running = f.isRunning(); // running == false +const bool finished = f.isFinished(); // finished == true +//! [36] + +//! [37] +QObject *context = ...; +auto future = ...; +auto continuation = future.then(context, [context](Result result) { + // ... + }).onCanceled([context = QPointer(context)] { + if (!context) + return; // context was destroyed already + // handle cancellation + }); + +//! [37] diff --git a/src/corelib/doc/snippets/code/src_corelib_thread_qmutexpool.cpp b/src/corelib/doc/snippets/code/src_corelib_thread_qmutexpool.cpp deleted file mode 100644 index 1368559b24..0000000000 --- a/src/corelib/doc/snippets/code/src_corelib_thread_qmutexpool.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause - -//! [0] -class Number { -public: - Number(double n) : num (n) { } - - void setNumber(double n) { num = n; } - double number() const { return num; } - -private: - double num; -}; -//! [0] - - -//! [1] -void calcSquare(Number *num) -{ - QMutexLocker locker(mutexpool.get(num)); - num.setNumber(num.number() * num.number()); -} -//! [1] diff --git a/src/corelib/doc/snippets/code/src_corelib_thread_qsemaphore.cpp b/src/corelib/doc/snippets/code/src_corelib_thread_qsemaphore.cpp index a46e10c7b0..d7c9b900af 100644 --- a/src/corelib/doc/snippets/code/src_corelib_thread_qsemaphore.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_thread_qsemaphore.cpp @@ -35,6 +35,12 @@ sem.tryAcquire(250, 1000); // sem.available() == 5, waits 1000 milliseconds a sem.tryAcquire(3, 30000); // sem.available() == 2, returns true without waiting //! [3] +//! [tryAcquire-QDeadlineTimer] +QSemaphore sem(5); // sem.available() == 5 +sem.tryAcquire(250, QDeadlineTimer(1000)); // sem.available() == 5, waits 1000 milliseconds and returns false +sem.tryAcquire(3, QDeadlineTimer(30s)); // sem.available() == 2, returns true without waiting +//! [tryAcquire-QDeadlineTimer] + //! [4] // ... do something that may throw or return early sem.release(); diff --git a/src/corelib/doc/snippets/code/src_corelib_time_qdatetime.cpp b/src/corelib/doc/snippets/code/src_corelib_time_qdatetime.cpp index 4563e81f30..588e81bab1 100644 --- a/src/corelib/doc/snippets/code/src_corelib_time_qdatetime.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_time_qdatetime.cpp @@ -71,14 +71,6 @@ QTime::isValid(22, 5, 62); // returns false //! [9] -//! [10] -QTime t; -t.start(); -some_lengthy_task(); -qDebug("Time elapsed: %d ms", t.elapsed()); -//! [10] - - //! [11] QDateTime now = QDateTime::currentDateTime(); QDateTime xmas(QDate(now.date().year(), 12, 25).startOfDay()); @@ -189,3 +181,11 @@ QDate firstMonday = 2020y / January / Monday[0]; // Last Monday of January 2020: QDate lastMonday = 2020y / January / Monday[last]; //! [22] + +//! [23] +QDateTime local(QDateTime::currentDateTime()); +QDateTime UTC(local.toTimeSpec(QTimeZone::UTC)); +qDebug() << "Local time is:" << local; +qDebug() << "UTC time is:" << UTC; +qDebug() << "No difference between times represented:" << local.secsTo(UTC); +//! [23] diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qcommandlineparser.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qcommandlineparser.cpp index 6fc3cf5c3c..cc22ba88ce 100644 --- a/src/corelib/doc/snippets/code/src_corelib_tools_qcommandlineparser.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_tools_qcommandlineparser.cpp @@ -90,12 +90,4 @@ Arguments: //! [3] } -{ -//! [4] -QCommandLineParser parser; -parser.setApplicationDescription(QCoreApplication::translate("main", "The best application in the world")); -parser.addHelpOption(); -//! [4] -} - } diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qhash.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qhash.cpp index f1be49c1d4..c779b9e3e7 100644 --- a/src/corelib/doc/snippets/code/src_corelib_tools_qhash.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_tools_qhash.cpp @@ -42,7 +42,7 @@ QHash<int, QWidget *> hash; ... for (int i = 0; i < 1000; ++i) { if (hash[i] == okButton) - cout << "Found button at index " << i << Qt::endl; + cout << "Found button at index " << i << endl; } //! [6] @@ -51,17 +51,14 @@ for (int i = 0; i < 1000; ++i) { QHashIterator<QString, int> i(hash); while (i.hasNext()) { i.next(); - cout << i.key() << ": " << i.value() << Qt::endl; + cout << qPrintable(i.key()) << ": " << i.value() << endl; } //! [7] //! [8] -QHash<QString, int>::const_iterator i = hash.constBegin(); -while (i != hash.constEnd()) { - cout << i.key() << ": " << i.value() << Qt::endl; - ++i; -} +for (auto i = hash.cbegin(), end = hash.cend(); i != end; ++i) + cout << qPrintable(i.key()) << ": " << i.value() << endl; //! [8] @@ -75,8 +72,8 @@ hash.insert("plenty", 2000); //! [12] QHash<QString, int> hash; ... -foreach (int value, hash) - cout << value << Qt::endl; +for (int value : std::as_const(hash)) + cout << value << endl; //! [12] @@ -138,7 +135,7 @@ QHash<QString, int> hash; ... QHash<QString, int>::const_iterator i = hash.find("HDR"); while (i != hash.end() && i.key() == "HDR") { - cout << i.value() << Qt::endl; + cout << i.value() << endl; ++i; } //! [16] @@ -151,50 +148,20 @@ hash.insert("February", 2); ... hash.insert("December", 12); -QHash<QString, int>::iterator i; -for (i = hash.begin(); i != hash.end(); ++i) - cout << i.key() << ": " << i.value() << Qt::endl; +for (auto i = hash.cbegin(), end = hash.cend(); i != end; ++i) + cout << qPrintable(key()) << ": " << i.value() << endl; //! [17] //! [18] -QHash<QString, int>::iterator i; -for (i = hash.begin(); i != hash.end(); ++i) +for (auto i = hash.begin(), end = hash.end(); i != end; ++i) i.value() += 2; //! [18] - -//! [19] -QHash<QString, int>::iterator i = hash.begin(); -while (i != hash.end()) { - if (i.key().startsWith('_')) - i = hash.erase(i); - else - ++i; -} -//! [19] - - -//! [20] -QHash<QString, int>::iterator i = hash.begin(); -while (i != hash.end()) { - QHash<QString, int>::iterator prev = i; - ++i; - if (prev.key().startsWith('_')) - hash.erase(prev); -} -//! [20] - - //! [21] -// WRONG -while (i != hash.end()) { - if (i.key().startsWith('_')) - hash.erase(i); - ++i; -} +erase_if(hash, [](const QHash<QString, int>::iterator it) { return it.value() > 10; }); //! [21] - +} //! [22] if (i.key() == "Hello") @@ -209,9 +176,8 @@ hash.insert("February", 2); ... hash.insert("December", 12); -QHash<QString, int>::const_iterator i; -for (i = hash.constBegin(); i != hash.constEnd(); ++i) - cout << i.key() << ": " << i.value() << Qt::endl; +for (auto i = hash.cbegin(), end = hash.cend(); i != end; ++i) + cout << qPrintable(i.key()) << ": " << i.value() << endl; //! [23] @@ -232,24 +198,24 @@ hash3 = hash1 + hash2; //! [25] QList<int> values = hash.values("plenty"); -for (int i = 0; i < values.size(); ++i) - cout << values.at(i) << Qt::endl; +for (auto i : std::as_const(values)) + cout << i << endl; //! [25] //! [26] -QMultiHash<QString, int>::iterator i = hash.find("plenty"); -while (i != hash.end() && i.key() == "plenty") { - cout << i.value() << Qt::endl; +auto i = hash.constFind("plenty"); +while (i != hash.cend() && i.key() == "plenty") { + cout << i.value() << endl; ++i; } //! [26] //! [27] -for (QHash<int, QString>::const_iterator it = hash.cbegin(), end = hash.cend(); it != end; ++it) { - cout << "The key: " << it.key() << Qt::endl - cout << "The value: " << it.value() << Qt::endl; - cout << "Also the value: " << (*it) << Qt::endl; +for (auto it = hash.cbegin(), end = hash.cend(); it != end; ++it) { + cout << "The key: " << it.key() << endl; + cout << "The value: " << qPrintable(it.value()) << endl; + cout << "Also the value: " << qPrintable(*it) << endl; } //! [27] @@ -297,11 +263,11 @@ inline size_t qHash(const std::unordered_set<int> &key, size_t seed = 0) //! [31] //! [32] -size_t qHash(K key); -size_t qHash(const K &key); - size_t qHash(K key, size_t seed); size_t qHash(const K &key, size_t seed); + +size_t qHash(K key); // deprecated, do not use +size_t qHash(const K &key); // deprecated, do not use //! [32] //! [33] @@ -322,7 +288,7 @@ hash.insert("February", 2); hash.insert("December", 12); for (auto [key, value] : hash.asKeyValueRange()) { - cout << key << ": " << value << Qt::endl; + cout << qPrintable(key) << ": " << value << endl; --value; // convert to JS month indexing } //! [34] @@ -335,7 +301,7 @@ hash.insert("February", 2); hash.insert("December", 12); for (auto [key, value] : hash.asKeyValueRange()) { - cout << key << ": " << value << Qt::endl; + cout << qPrintable(key) << ": " << value << endl; --value; // convert to JS month indexing } //! [35] diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qlist.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qlist.cpp index 8957d43476..499e8fe480 100644 --- a/src/corelib/doc/snippets/code/src_corelib_tools_qlist.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_tools_qlist.cpp @@ -26,7 +26,7 @@ if (list[0] == "Liz") //! [4] for (qsizetype i = 0; i < list.size(); ++i) { if (list.at(i) == "Alfonso") - cout << "Found Alfonso at position " << i << Qt::endl; + cout << "Found Alfonso at position " << i << endl; } //! [4] @@ -34,7 +34,7 @@ for (qsizetype i = 0; i < list.size(); ++i) { //! [5] qsizetype i = list.indexOf("Harumi"); if (i != -1) - cout << "First occurrence of Harumi is at position " << i << Qt::endl; + cout << "First occurrence of Harumi is at position " << i << endl; //! [5] @@ -101,16 +101,14 @@ list.prepend("three"); //! [9] -QList<QString> list; -list << "alpha" << "beta" << "delta"; +QList<QString> list = {"alpha", "beta", "delta"}; list.insert(2, "gamma"); // list: ["alpha", "beta", "gamma", "delta"] //! [9] //! [10] -QList<double> list; -list << 2.718 << 1.442 << 0.4342; +QList<double> list = {2.718, 1.442, 0.4342}; list.insert(1, 3, 9.9); // list: [2.718, 9.9, 9.9, 9.9, 1.442, 0.4342] //! [10] @@ -127,8 +125,7 @@ list.fill("oh", 5); //! [12] -QList<QString> list; -list << "A" << "B" << "C" << "B" << "A"; +QList<QString> list{"A", "B", "C", "B", "A"}; list.indexOf("B"); // returns 1 list.indexOf("B", 1); // returns 1 list.indexOf("B", 2); // returns 3 @@ -137,8 +134,7 @@ list.indexOf("X"); // returns -1 //! [13] -QList<QString> list; -list << "A" << "B" << "C" << "B" << "A"; +QList<QString> list = {"A", "B", "C", "B", "A"}; list.lastIndexOf("B"); // returns 3 list.lastIndexOf("B", 3); // returns 3 list.lastIndexOf("B", 2); // returns 1 diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qmap.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qmap.cpp index 552b7be80a..5f87211968 100644 --- a/src/corelib/doc/snippets/code/src_corelib_tools_qmap.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_tools_qmap.cpp @@ -42,7 +42,7 @@ QMap<int, QWidget *> map; ... for (int i = 0; i < 1000; ++i) { if (map[i] == okButton) - cout << "Found button at index " << i << Qt::endl; + cout << "Found button at index " << i << endl; } //! [6] @@ -51,17 +51,14 @@ for (int i = 0; i < 1000; ++i) { QMapIterator<QString, int> i(map); while (i.hasNext()) { i.next(); - cout << i.key() << ": " << i.value() << Qt::endl; + cout << qPrintable(i.key()) << ": " << i.value() << endl; } //! [7] //! [8] -QMap<QString, int>::const_iterator i = map.constBegin(); -while (i != map.constEnd()) { - cout << i.key() << ": " << i.value() << Qt::endl; - ++i; -} +for (auto i = map.cbegin(), end = map.cend(); i != end; ++i) + cout << qPrintable(i.key()) << ": " << i.value() << endl; //! [8] @@ -75,8 +72,8 @@ map.insert("plenty", 2000); //! [12] QMap<QString, int> map; ... -foreach (int value, map) - cout << value << Qt::endl; +for (int value : std::as_const(map)) + cout << value << endl; //! [12] @@ -107,43 +104,6 @@ inline bool operator<(const Employee &e1, const Employee &e2) //! [13] -//! [14] -QMap<QString, int> map; -... -QMap<QString, int>::const_iterator i = map.find("HDR"); -while (i != map.end() && i.key() == "HDR") { - cout << i.value() << Qt::endl; - ++i; -} -//! [14] - - -//! [15] -QMap<int, QString> map; -map.insert(1, "one"); -map.insert(5, "five"); -map.insert(10, "ten"); - -map.lowerBound(0); // returns iterator to (1, "one") -map.lowerBound(1); // returns iterator to (1, "one") -map.lowerBound(2); // returns iterator to (5, "five") -map.lowerBound(10); // returns iterator to (10, "ten") -map.lowerBound(999); // returns end() -//! [15] - - -//! [16] -QMap<QString, int> map; -... -QMap<QString, int>::const_iterator i = map.lowerBound("HDR"); -QMap<QString, int>::const_iterator upperBound = map.upperBound("HDR"); -while (i != upperBound) { - cout << i.value() << Qt::endl; - ++i; -} -//! [16] - - //! [17] QMap<int, QString> map; map.insert(1, "one"); @@ -165,50 +125,33 @@ map.insert("February", 2); ... map.insert("December", 12); -QMap<QString, int>::iterator i; -for (i = map.begin(); i != map.end(); ++i) - cout << i.key() << ": " << i.value() << Qt::endl; +for (auto i = map.cbegin(), end = map.cend(); i != end; ++i) + cout << qPrintable(i.key()) << ": " << i.value() << endl; //! [18] //! [19] -QMap<QString, int>::iterator i; -for (i = map.begin(); i != map.end(); ++i) +for (auto i = map.begin(), end = map.end(); i != end; ++i) i.value() += 2; //! [19] +void erase() +{ +QMap<QString, int> map; //! [20] -QMap<QString, int>::iterator i = map.begin(); -while (i != map.end()) { - if (i.key().startsWith('_')) +QMap<QString, int>::const_iterator i = map.cbegin(); +while (i != map.cend()) { + if (i.value() > 10) i = map.erase(i); else ++i; } //! [20] - - //! [21] -QMap<QString, int>::iterator i = map.begin(); -while (i != map.end()) { - QMap<QString, int>::iterator prev = i; - ++i; - if (prev.key().startsWith('_')) - map.erase(prev); -} +erase_if(map, [](const QMap<QString, int>::iterator it) { return it.value() > 10; }); //! [21] - - -//! [22] -// WRONG -while (i != map.end()) { - if (i.key().startsWith('_')) - map.erase(i); - ++i; } -//! [22] - //! [23] if (i.key() == "Hello") @@ -223,47 +166,16 @@ map.insert("February", 2); ... map.insert("December", 12); -QMap<QString, int>::const_iterator i; -for (i = map.constBegin(); i != map.constEnd(); ++i) - cout << i.key() << ": " << i.value() << Qt::endl; +for (auto i = map.cbegin(), end = map.cend(); i != end; ++i) + cout << qPrintable(i.key()) << ": " << i.value() << endl; //! [24] -//! [25] -QMultiMap<QString, int> map1, map2, map3; - -map1.insert("plenty", 100); -map1.insert("plenty", 2000); -// map1.size() == 2 - -map2.insert("plenty", 5000); -// map2.size() == 1 - -map3 = map1 + map2; -// map3.size() == 3 -//! [25] - - -//! [26] -QList<int> values = map.values("plenty"); -for (int i = 0; i < values.size(); ++i) - cout << values.at(i) << Qt::endl; -//! [26] - - -//! [27] -QMultiMap<QString, int>::iterator i = map.find("plenty"); -while (i != map.end() && i.key() == "plenty") { - cout << i.value() << Qt::endl; - ++i; -} -//! [27] - //! [keyiterator1] for (QMap<int, QString>::const_iterator it = map.cbegin(), end = map.cend(); it != end; ++it) { - cout << "The key: " << it.key() << Qt::endl - cout << "The value: " << it.value() << Qt::endl; - cout << "Also the value: " << (*it) << Qt::endl; + cout << "The key: " << it.key() << endl; + cout << "The value: " << qPrintable(it.value()) << endl; + cout << "Also the value: " << qPrintable(*it) << endl; } //! [keyiterator1] @@ -286,7 +198,7 @@ map.insert("February", 2); map.insert("December", 12); for (auto [key, value] : map.asKeyValueRange()) { - cout << key << ": " << value << Qt::endl; + cout << qPrintable(key) << ": " << value << endl; --value; // convert to JS month indexing } //! [28] diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qmultimap.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qmultimap.cpp index 60793ab111..42ec46585b 100644 --- a/src/corelib/doc/snippets/code/src_corelib_tools_qmultimap.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_tools_qmultimap.cpp @@ -19,8 +19,8 @@ multimap.insert("c", -5); int num2 = multimap.value("a"); // 1 int num3 = multimap.value("thirteen"); // not found; 0 int num3 = 0; -auto it = multimap.value("b"); -if (it != multimap.end()) { +auto it = multimap.constFind("b"); +if (it != multimap.cend()) { num3 = it.value(); } //! [3] @@ -47,17 +47,14 @@ int timeout = multimap.value("TIMEOUT", 30); QMultiMapIterator<QString, int> i(multimap); while (i.hasNext()) { i.next(); - cout << i.key() << ": " << i.value() << Qt::endl; + cout << qPrintable(i.key()) << ": " << i.value() << endl; } //! [7] //! [8] -auto i = multimap.constBegin(); -while (i != multimap.constEnd()) { - cout << i.key() << ": " << i.value() << Qt::endl; - ++i; -} +for (auto i = multimap.cbegin(), end = multimap.cend(); i != end; ++i) + cout << qPrintable(i.key()) << ": " << i.value() << endl; //! [8] @@ -70,22 +67,22 @@ multimap.insert("plenty", 2000); //! [10] QList<int> values = multimap.values("plenty"); -for (int i = 0; i < values.size(); ++i) - cout << values.at(i) << Qt::endl; +for (auto i : std::as_const(values)) + cout << i << endl; //! [10] //! [11] -QMultiMap<QString, int>::iterator i = multimap.find("plenty"); +auto i = multimap.find("plenty"); while (i != map.end() && i.key() == "plenty") { - cout << i.value() << Qt::endl; + cout << i.value() << endl; ++i; } // better: auto [i, end] = multimap.equal_range("plenty"); while (i != end) { - cout << i.value() << Qt::endl; + cout << i.value() << endl; ++i; } //! [11] @@ -94,8 +91,8 @@ while (i != end) { //! [12] QMap<QString, int> multimap; ... -foreach (int value, multimap) - cout << value << Qt::endl; +for (int value : std::as_const(multimap)) + cout << value << endl; //! [12] @@ -149,7 +146,7 @@ QMap<QString, int> multimap; QMap<QString, int>::const_iterator i = multimap.lowerBound("HDR"); QMap<QString, int>::const_iterator upperBound = multimap.upperBound("HDR"); while (i != upperBound) { - cout << i.value() << Qt::endl; + cout << i.value() << endl; ++i; } //! [16] @@ -171,57 +168,27 @@ multimap.upperBound(10); // returns end() multimap.upperBound(999); // returns end() //! [17] - -//! [18] -QMultiMap<QString, int> multimap; -multimap.insert("January", 1); -multimap.insert("February", 2); -... -multimap.insert("December", 12); - -QMap<QString, int>::iterator i; -for (i = multimap.begin(); i != multimap.end(); ++i) - cout << i.key() << ": " << i.value() << Qt::endl; -//! [18] - - //! [19] -QMultiMap<QString, int>::iterator i; -for (i = multimap.begin(); i != multimap.end(); ++i) +for (auto it = multimap.begin(), end = multimap.end(); i != end; ++i) i.value() += 2; //! [19] - +void erase() +{ +QMultiMap<QString, int> multimap; //! [20] -QMultiMap<QString, int>::iterator i = multimap.begin(); -while (i != multimap.end()) { - if (i.key().startsWith('_')) +QMultiMap<QString, int>::const_iterator i = multimap.cbegin(); +while (i != multimap.cend()) { + if (i.value() > 10) i = multimap.erase(i); else ++i; } //! [20] - - //! [21] -QMultiMap<QString, int>::iterator i = multimap.begin(); -while (i != multimap.end()) { - QMap<QString, int>::iterator prev = i; - ++i; - if (prev.key().startsWith('_')) - multimap.erase(prev); -} +erase_if(multimap, [](const QMultiMap<QString, int>::iterator it) { return it.value() > 10; }); //! [21] - - -//! [22] -// WRONG -while (i != multimap.end()) { - if (i.key().startsWith('_')) - multimap.erase(i); - ++i; } -//! [22] //! [23] @@ -237,9 +204,8 @@ multimap.insert("February", 2); ... multimap.insert("December", 12); -QMultiMap<QString, int>::const_iterator i; -for (i = multimap.constBegin(); i != multimap.constEnd(); ++i) - cout << i.key() << ": " << i.value() << Qt::endl; +for (auto i = multimap.cbegin(), end = multimap.cend(); i != end; ++i) + cout << qPrintable(i.key()) << ": " << i.value() << endl; //! [24] @@ -258,10 +224,10 @@ map3 = map1 + map2; //! [25] //! [keyiterator1] -for (QMultiMap<int, QString>::const_iterator it = multimap.cbegin(), end = multimap.cend(); it != end; ++it) { - cout << "The key: " << it.key() << Qt::endl - cout << "The value: " << it.value() << Qt::endl; - cout << "Also the value: " << (*it) << Qt::endl; +for (auto it = multimap.cbegin(), end = multimap.cend(); it != end; ++it) { + cout << "The key: " << it.key() << endl + cout << "The value: " << qPrintable(it.value()) << endl; + cout << "Also the value: " << qPrintable(*it) << endl; } //! [keyiterator1] @@ -284,7 +250,7 @@ map.insert("February", 2); map.insert("December", 12); for (auto [key, value] : map.asKeyValueRange()) { - cout << key << ": " << value << Qt::endl; + cout << qPrintable(key) << ": " << value << endl; --value; // convert to JS month indexing } //! [26] diff --git a/src/corelib/doc/snippets/code/src_corelib_tools_qqueue.cpp b/src/corelib/doc/snippets/code/src_corelib_tools_qqueue.cpp index 81b8eb4dbd..c59ec1060a 100644 --- a/src/corelib/doc/snippets/code/src_corelib_tools_qqueue.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_tools_qqueue.cpp @@ -7,5 +7,5 @@ queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); while (!queue.isEmpty()) - cout << queue.dequeue() << Qt::endl; + cout << queue.dequeue() << endl; //! [0] diff --git a/src/corelib/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp b/src/corelib/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp deleted file mode 100644 index afa4c09873..0000000000 --- a/src/corelib/doc/snippets/code/src_gui_dialogs_qmessagebox.cpp +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (C) 2021 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause - -//! [0] -int ret = QMessageBox::warning(this, tr("My Application"), - tr("The document has been modified.\n" - "Do you want to save your changes?"), - QMessageBox::Save | QMessageBox::Discard - | QMessageBox::Cancel, - QMessageBox::Save); -//! [0] - - -//! [1] -QMessageBox msgBox; -msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); -switch (msgBox.exec()) { -case QMessageBox::Yes: - // yes was clicked - break; -case QMessageBox::No: - // no was clicked - break; -default: - // should never be reached - break; -} -//! [1] - - -//! [2] -QMessageBox msgBox; -QPushButton *connectButton = msgBox.addButton(tr("Connect"), QMessageBox::ActionRole); -QPushButton *abortButton = msgBox.addButton(QMessageBox::Abort); - -msgBox.exec(); - -if (msgBox.clickedButton() == connectButton) { - // connect -} else if (msgBox.clickedButton() == abortButton) { - // abort -} -//! [2] - - -//! [3] -QMessageBox messageBox(this); -QAbstractButton *disconnectButton = - messageBox.addButton(tr("Disconnect"), QMessageBox::ActionRole); -... -messageBox.exec(); -if (messageBox.clickedButton() == disconnectButton) { - ... -} -//! [3] - - -//! [4] -#include <QApplication> -#include <QMessageBox> - -int main(int argc, char *argv[]) -{ - QT_REQUIRE_VERSION(argc, argv, "6.1.2") - - QApplication app(argc, argv); - ... - return app.exec(); -} -//! [4] - -//! [5] -QMessageBox msgBox; -msgBox.setText("The document has been modified."); -msgBox.exec(); -//! [5] - -//! [6] -QMessageBox msgBox; -msgBox.setText("The document has been modified."); -msgBox.setInformativeText("Do you want to save your changes?"); -msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); -msgBox.setDefaultButton(QMessageBox::Save); -int ret = msgBox.exec(); -//! [6] - -//! [7] -switch (ret) { - case QMessageBox::Save: - // Save was clicked - break; - case QMessageBox::Discard: - // Don't Save was clicked - break; - case QMessageBox::Cancel: - // Cancel was clicked - break; - default: - // should never be reached - break; -} -//! [7] - -//! [9] -QMessageBox msgBox(this); -msgBox.setText(tr("The document has been modified.\n" - "Do you want to save your changes?")); -msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard - | QMessageBox::Cancel); -msgBox.setDefaultButton(QMessageBox::Save); -//! [9] diff --git a/src/corelib/doc/snippets/code/src_gui_itemviews_qidentityproxymodel.cpp b/src/corelib/doc/snippets/code/src_gui_itemviews_qidentityproxymodel.cpp index 52934b6159..4ef1891cdb 100644 --- a/src/corelib/doc/snippets/code/src_gui_itemviews_qidentityproxymodel.cpp +++ b/src/corelib/doc/snippets/code/src_gui_itemviews_qidentityproxymodel.cpp @@ -17,10 +17,16 @@ class DateFormatProxyModel : public QIdentityProxyModel return QIdentityProxyModel::data(index, role); const QDateTime dateTime = sourceModel()->data(SourceClass::DateRole).toDateTime(); - return dateTime.toString(m_formatString); } + QMap<int, QVariant> itemData(const QModelIndex &proxyIndex) const override + { + QMap<int, QVariant> map = QIdentityProxyModel::itemData(proxyIndex); + map[Qt::DisplayRole] = data(proxyIndex); + return map; + } + private: QString m_formatString; }; |