diff options
Diffstat (limited to 'examples')
20 files changed, 136 insertions, 87 deletions
diff --git a/examples/network/downloadmanager/downloadmanager.cpp b/examples/network/downloadmanager/downloadmanager.cpp index e820b4ff70..9e0c03c6af 100644 --- a/examples/network/downloadmanager/downloadmanager.cpp +++ b/examples/network/downloadmanager/downloadmanager.cpp @@ -132,7 +132,7 @@ void DownloadManager::startNextDownload() // prepare the output printf("Downloading %s...\n", url.toEncoded().constData()); - downloadTime.start(); + downloadTimer.start(); } void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) @@ -140,7 +140,7 @@ void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) progressBar.setStatus(bytesReceived, bytesTotal); // calculate the download speed - double speed = bytesReceived * 1000.0 / downloadTime.elapsed(); + double speed = bytesReceived * 1000.0 / downloadTimer.elapsed(); QString unit; if (speed < 1024) { unit = "bytes/sec"; diff --git a/examples/network/downloadmanager/downloadmanager.h b/examples/network/downloadmanager/downloadmanager.h index 4bc6351ff9..818a774f1f 100644 --- a/examples/network/downloadmanager/downloadmanager.h +++ b/examples/network/downloadmanager/downloadmanager.h @@ -83,7 +83,7 @@ private: QQueue<QUrl> downloadQueue; QNetworkReply *currentDownload = nullptr; QFile output; - QTime downloadTime; + QElapsedTimer downloadTimer; TextProgressBar progressBar; int downloadedCount = 0; diff --git a/examples/network/secureudpserver/server.cpp b/examples/network/secureudpserver/server.cpp index 0d83fa9b51..450eb9e68d 100644 --- a/examples/network/secureudpserver/server.cpp +++ b/examples/network/secureudpserver/server.cpp @@ -62,7 +62,7 @@ QString peer_info(const QHostAddress &address, quint16 port) return info.arg(address.toString()).arg(port); } -QString connection_info(QSharedPointer<QDtls> connection) +QString connection_info(QDtls *connection) { QString info(DtlsServer::tr("Session cipher: ")); info += connection->sessionCipher().name(); @@ -157,7 +157,7 @@ void DtlsServer::readyRead() } const auto client = std::find_if(knownClients.begin(), knownClients.end(), - [&](const DtlsConnection &connection){ + [&](const std::unique_ptr<QDtls> &connection){ return connection->peerAddress() == peerAddress && connection->peerPort() == peerPort; }); @@ -170,7 +170,7 @@ void DtlsServer::readyRead() //! [6] if ((*client)->isConnectionEncrypted()) { - decryptDatagram(*client, dgram); + decryptDatagram(client->get(), dgram); if ((*client)->dtlsError() == QDtlsError::RemoteClosedConnectionError) knownClients.erase(client); return; @@ -178,7 +178,7 @@ void DtlsServer::readyRead() //! [6] //! [7] - doHandshake(*client, dgram); + doHandshake(client->get(), dgram); //! [7] } @@ -205,13 +205,13 @@ void DtlsServer::handleNewConnection(const QHostAddress &peerAddress, emit infoMessage(peerInfo + tr(": verified, starting a handshake")); //! [8] //! [9] - DtlsConnection newConnection(new QDtls(QSslSocket::SslServerMode)); + std::unique_ptr<QDtls> newConnection{new QDtls{QSslSocket::SslServerMode}}; newConnection->setDtlsConfiguration(serverConfiguration); newConnection->setPeer(peerAddress, peerPort); - newConnection->connect(newConnection.data(), &QDtls::pskRequired, + newConnection->connect(newConnection.get(), &QDtls::pskRequired, this, &DtlsServer::pskRequired); - knownClients.push_back(newConnection); - doHandshake(newConnection, clientHello); + knownClients.push_back(std::move(newConnection)); + doHandshake(knownClients.back().get(), clientHello); //! [9] } else if (cookieSender.dtlsError() != QDtlsError::NoError) { emit errorMessage(tr("DTLS error: ") + cookieSender.dtlsErrorString()); @@ -221,7 +221,7 @@ void DtlsServer::handleNewConnection(const QHostAddress &peerAddress, } //! [11] -void DtlsServer::doHandshake(DtlsConnection newConnection, const QByteArray &clientHello) +void DtlsServer::doHandshake(QDtls *newConnection, const QByteArray &clientHello) { const bool result = newConnection->doHandshake(&serverSocket, clientHello); if (!result) { @@ -246,7 +246,7 @@ void DtlsServer::doHandshake(DtlsConnection newConnection, const QByteArray &cli //! [11] //! [12] -void DtlsServer::decryptDatagram(DtlsConnection connection, const QByteArray &clientMessage) +void DtlsServer::decryptDatagram(QDtls *connection, const QByteArray &clientMessage) { Q_ASSERT(connection->isConnectionEncrypted()); @@ -266,10 +266,9 @@ void DtlsServer::decryptDatagram(DtlsConnection connection, const QByteArray &cl //! [14] void DtlsServer::shutdown() { - for (DtlsConnection &connection : knownClients) + for (const auto &connection : qExchange(knownClients, {})) connection->shutdown(&serverSocket); - knownClients.clear(); serverSocket.close(); } //! [14] diff --git a/examples/network/secureudpserver/server.h b/examples/network/secureudpserver/server.h index b720368e7b..1af8aef8a2 100644 --- a/examples/network/secureudpserver/server.h +++ b/examples/network/secureudpserver/server.h @@ -54,6 +54,7 @@ #include <QtNetwork> #include <vector> +#include <memory> QT_BEGIN_NAMESPACE @@ -86,9 +87,8 @@ private: void handleNewConnection(const QHostAddress &peerAddress, quint16 peerPort, const QByteArray &clientHello); - using DtlsConnection = QSharedPointer<QDtls>; - void doHandshake(DtlsConnection newConnection, const QByteArray &clientHello); - void decryptDatagram(DtlsConnection connection, const QByteArray &clientMessage); + void doHandshake(QDtls *newConnection, const QByteArray &clientHello); + void decryptDatagram(QDtls *connection, const QByteArray &clientMessage); void shutdown(); bool listening = false; @@ -96,7 +96,7 @@ private: QSslConfiguration serverConfiguration; QDtlsClientVerifier cookieSender; - QVector<DtlsConnection> knownClients; + std::vector<std::unique_ptr<QDtls>> knownClients; Q_DISABLE_COPY(DtlsServer) }; diff --git a/examples/network/torrent/ratecontroller.cpp b/examples/network/torrent/ratecontroller.cpp index 87c65096b6..96474806f5 100644 --- a/examples/network/torrent/ratecontroller.cpp +++ b/examples/network/torrent/ratecontroller.cpp @@ -96,8 +96,8 @@ void RateController::transfer() if (sockets.isEmpty()) return; - int msecs = 1000; - if (!stopWatch.isNull()) + qint64 msecs = 1000; + if (stopWatch.isValid()) msecs = qMin(msecs, stopWatch.elapsed()); qint64 bytesToWrite = (upLimit * msecs) / 1000; diff --git a/examples/network/torrent/ratecontroller.h b/examples/network/torrent/ratecontroller.h index a4aa596ce1..f8bff0cc36 100644 --- a/examples/network/torrent/ratecontroller.h +++ b/examples/network/torrent/ratecontroller.h @@ -53,7 +53,7 @@ #include <QObject> #include <QSet> -#include <QTime> +#include <QElapsedTimer> class PeerWireClient; @@ -79,7 +79,7 @@ public slots: void scheduleTransfer(); private: - QTime stopWatch; + QElapsedTimer stopWatch; QSet<PeerWireClient *> sockets; int upLimit; int downLimit; diff --git a/examples/opengl/qopenglwidget/glwidget.h b/examples/opengl/qopenglwidget/glwidget.h index de7805a907..0ad2581cb8 100644 --- a/examples/opengl/qopenglwidget/glwidget.h +++ b/examples/opengl/qopenglwidget/glwidget.h @@ -56,7 +56,7 @@ #include <QOpenGLBuffer> #include <QVector3D> #include <QMatrix4x4> -#include <QTime> +#include <QElapsedTimer> #include <QVector> #include <QPushButton> @@ -106,7 +106,7 @@ private: bool m_qtLogo; QList<Bubble *> m_bubbles; int m_frames; - QTime m_time; + QElapsedTimer m_time; QOpenGLShader *m_vshader1; QOpenGLShader *m_fshader1; QOpenGLShader *m_vshader2; diff --git a/examples/qtconcurrent/wordcount/main.cpp b/examples/qtconcurrent/wordcount/main.cpp index 32cb4d0e08..ae8542a761 100644 --- a/examples/qtconcurrent/wordcount/main.cpp +++ b/examples/qtconcurrent/wordcount/main.cpp @@ -54,7 +54,7 @@ #include <QString> #include <QStringList> #include <QDir> -#include <QTime> +#include <QElapsedTimer> #include <QApplication> #include <QDebug> @@ -146,19 +146,19 @@ int main(int argc, char** argv) int singleThreadTime = 0; { - QTime time; - time.start(); + QElapsedTimer timer; + timer.start(); WordCount total = singleThreadedWordCount(files); - singleThreadTime = time.elapsed(); + singleThreadTime = timer.elapsed(); qDebug() << "single thread" << singleThreadTime; } int mapReduceTime = 0; { - QTime time; - time.start(); + QElapsedTimer timer; + timer.start(); WordCount total = mappedReduced(files, countWords, reduce); - mapReduceTime = time.elapsed(); + mapReduceTime = timer.elapsed(); qDebug() << "MapReduce" << mapReduceTime; } qDebug() << "MapReduce speedup x" << ((double)singleThreadTime - (double)mapReduceTime) / (double)mapReduceTime + 1; diff --git a/examples/sql/books/initdb.h b/examples/sql/books/initdb.h index 44f74f0c37..773e3fb74c 100644 --- a/examples/sql/books/initdb.h +++ b/examples/sql/books/initdb.h @@ -79,6 +79,32 @@ QVariant addAuthor(QSqlQuery &q, const QString &name, const QDate &birthdate) return q.lastInsertId(); } +const auto BOOKS_SQL = QLatin1String(R"( + create table books(id integer primary key, title varchar, author integer, + genre integer, year integer, rating integer) + )"); + +const auto AUTHORS_SQL = QLatin1String(R"( + create table authors(id integer primary key, name varchar, birthdate date) + )"); + +const auto GENRES_SQL = QLatin1String(R"( + create table genres(id integer primary key, name varchar) + )"); + +const auto INSERT_AUTHOR_SQL = QLatin1String(R"( + insert into authors(name, birthdate) values(?, ?) + )"); + +const auto INSERT_BOOK_SQL = QLatin1String(R"( + insert into books(title, year, author, genre, rating) + values(?, ?, ?, ?, ?) + )"); + +const auto INSERT_GENRE_SQL = QLatin1String(R"( + insert into genres(name) values(?) + )"); + QSqlError initDb() { QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); @@ -93,26 +119,26 @@ QSqlError initDb() return QSqlError(); QSqlQuery q; - if (!q.exec(QLatin1String("create table books(id integer primary key, title varchar, author integer, genre integer, year integer, rating integer)"))) + if (!q.exec(BOOKS_SQL)) return q.lastError(); - if (!q.exec(QLatin1String("create table authors(id integer primary key, name varchar, birthdate date)"))) + if (!q.exec(AUTHORS_SQL)) return q.lastError(); - if (!q.exec(QLatin1String("create table genres(id integer primary key, name varchar)"))) + if (!q.exec(GENRES_SQL)) return q.lastError(); - if (!q.prepare(QLatin1String("insert into authors(name, birthdate) values(?, ?)"))) + if (!q.prepare(INSERT_AUTHOR_SQL)) return q.lastError(); QVariant asimovId = addAuthor(q, QLatin1String("Isaac Asimov"), QDate(1920, 2, 1)); QVariant greeneId = addAuthor(q, QLatin1String("Graham Greene"), QDate(1904, 10, 2)); QVariant pratchettId = addAuthor(q, QLatin1String("Terry Pratchett"), QDate(1948, 4, 28)); - if (!q.prepare(QLatin1String("insert into genres(name) values(?)"))) + if (!q.prepare(INSERT_GENRE_SQL)) return q.lastError(); QVariant sfiction = addGenre(q, QLatin1String("Science Fiction")); QVariant fiction = addGenre(q, QLatin1String("Fiction")); QVariant fantasy = addGenre(q, QLatin1String("Fantasy")); - if (!q.prepare(QLatin1String("insert into books(title, year, author, genre, rating) values(?, ?, ?, ?, ?)"))) + if (!q.prepare(INSERT_BOOK_SQL)) return q.lastError(); addBook(q, QLatin1String("Foundation"), 1951, asimovId, sfiction, 3); addBook(q, QLatin1String("Foundation and Empire"), 1952, asimovId, sfiction, 4); diff --git a/examples/widgets/doc/src/application.qdoc b/examples/widgets/doc/src/application.qdoc index 040aa171b7..6c37fa67bb 100644 --- a/examples/widgets/doc/src/application.qdoc +++ b/examples/widgets/doc/src/application.qdoc @@ -327,9 +327,12 @@ \snippet mainwindows/application/mainwindow.cpp 44 \snippet mainwindows/application/mainwindow.cpp 45 - Saving a file is very similar to loading one. Here, the - QFile::Text flag ensures that on Windows, "\\n" is converted into - "\\r\\n" to conform to the Windows convension. + Saving a file is similar to loading one. We use QSaveFile to ensure + all data are safely written and existing files are not damaged + should writing fail. + We use the QFile::Text flag to make sure that on Windows, "\\n" + is converted into "\\r\\n" to conform to the Windows convention. + \snippet mainwindows/application/mainwindow.cpp 46 \snippet mainwindows/application/mainwindow.cpp 47 diff --git a/examples/widgets/doc/src/classwizard.qdoc b/examples/widgets/doc/src/classwizard.qdoc index 6977cf5efa..7f3693b65e 100644 --- a/examples/widgets/doc/src/classwizard.qdoc +++ b/examples/widgets/doc/src/classwizard.qdoc @@ -30,7 +30,7 @@ \title Class Wizard Example \ingroup examples-dialogs - \brief The License Wizard example shows how to implement linear + \brief The Class Wizard example shows how to implement linear wizards using QWizard. \image classwizard.png Screenshot of the Class Wizard example diff --git a/examples/widgets/doc/src/stardelegate.qdoc b/examples/widgets/doc/src/stardelegate.qdoc index 0b91723a51..b33fa3550f 100644 --- a/examples/widgets/doc/src/stardelegate.qdoc +++ b/examples/widgets/doc/src/stardelegate.qdoc @@ -269,7 +269,7 @@ \codeline \snippet itemviews/stardelegate/main.cpp 4 - Notice the call to qVariantFromValue to convert a \c + Notice the call to QVariant::fromValue to convert a \c StarRating to a QVariant. \section1 Possible Extensions and Suggestions diff --git a/examples/widgets/graphicsview/boxes/scene.cpp b/examples/widgets/graphicsview/boxes/scene.cpp index 7f62ac894b..d51124aed7 100644 --- a/examples/widgets/graphicsview/boxes/scene.cpp +++ b/examples/widgets/graphicsview/boxes/scene.cpp @@ -533,8 +533,6 @@ Scene::Scene(int width, int height, int maxTextureSize) m_timer->setInterval(20); connect(m_timer, &QTimer::timeout, this, [this](){ update(); }); m_timer->start(); - - m_time.start(); } Scene::~Scene() diff --git a/examples/widgets/graphicsview/boxes/scene.h b/examples/widgets/graphicsview/boxes/scene.h index ccb6f368cd..ffff01358f 100644 --- a/examples/widgets/graphicsview/boxes/scene.h +++ b/examples/widgets/graphicsview/boxes/scene.h @@ -220,7 +220,7 @@ private: void initGL(); QPointF pixelPosToViewPos(const QPointF& p); - QTime m_time; + QTime m_time; // ### Qt 6: remove (unused) int m_lastTime; int m_mouseEventTime; int m_distExp; diff --git a/examples/widgets/mainwindows/application/mainwindow.cpp b/examples/widgets/mainwindows/application/mainwindow.cpp index 4b639ead18..7886c4afac 100644 --- a/examples/widgets/mainwindows/application/mainwindow.cpp +++ b/examples/widgets/mainwindows/application/mainwindow.cpp @@ -353,23 +353,27 @@ void MainWindow::loadFile(const QString &fileName) bool MainWindow::saveFile(const QString &fileName) //! [44] //! [45] { - QFile file(fileName); - if (!file.open(QFile::WriteOnly | QFile::Text)) { - QMessageBox::warning(this, tr("Application"), - tr("Cannot write file %1:\n%2.") - .arg(QDir::toNativeSeparators(fileName), - file.errorString())); - return false; - } + QString errorMessage; - QTextStream out(&file); -#ifndef QT_NO_CURSOR QGuiApplication::setOverrideCursor(Qt::WaitCursor); -#endif - out << textEdit->toPlainText(); -#ifndef QT_NO_CURSOR + QSaveFile file(fileName); + if (file.open(QFile::WriteOnly | QFile::Text)) { + QTextStream out(&file); + out << textEdit->toPlainText(); + if (!file.commit()) { + errorMessage = tr("Cannot write file %1:\n%2.") + .arg(QDir::toNativeSeparators(fileName), file.errorString()); + } + } else { + errorMessage = tr("Cannot open file %1 for writing:\n%2.") + .arg(QDir::toNativeSeparators(fileName), file.errorString()); + } QGuiApplication::restoreOverrideCursor(); -#endif + + if (!errorMessage.isEmpty()) { + QMessageBox::warning(this, tr("Application"), errorMessage); + return false; + } setCurrentFile(fileName); statusBar()->showMessage(tr("File saved"), 2000); diff --git a/examples/widgets/mainwindows/mdi/mdichild.cpp b/examples/widgets/mainwindows/mdi/mdichild.cpp index 16f2040de0..727d4f6cfd 100644 --- a/examples/widgets/mainwindows/mdi/mdichild.cpp +++ b/examples/widgets/mainwindows/mdi/mdichild.cpp @@ -115,19 +115,28 @@ bool MdiChild::saveAs() bool MdiChild::saveFile(const QString &fileName) { - QFile file(fileName); - if (!file.open(QFile::WriteOnly | QFile::Text)) { - QMessageBox::warning(this, tr("MDI"), - tr("Cannot write file %1:\n%2.") - .arg(QDir::toNativeSeparators(fileName), file.errorString())); - return false; - } + QString errorMessage; - QTextStream out(&file); QGuiApplication::setOverrideCursor(Qt::WaitCursor); - out << toPlainText(); + QSaveFile file(fileName); + if (file.open(QFile::WriteOnly | QFile::Text)) { + QTextStream out(&file); + out << toPlainText(); + if (!file.commit()) { + errorMessage = tr("Cannot write file %1:\n%2.") + .arg(QDir::toNativeSeparators(fileName), file.errorString()); + } + } else { + errorMessage = tr("Cannot open file %1 for writing:\n%2.") + .arg(QDir::toNativeSeparators(fileName), file.errorString()); + } QGuiApplication::restoreOverrideCursor(); + if (!errorMessage.isEmpty()) { + QMessageBox::warning(this, tr("MDI"), errorMessage); + return false; + } + setCurrentFile(fileName); return true; } diff --git a/examples/widgets/mainwindows/sdi/mainwindow.cpp b/examples/widgets/mainwindows/sdi/mainwindow.cpp index 62a74b26e6..a1fb42158e 100644 --- a/examples/widgets/mainwindows/sdi/mainwindow.cpp +++ b/examples/widgets/mainwindows/sdi/mainwindow.cpp @@ -425,19 +425,28 @@ void MainWindow::openRecentFile() bool MainWindow::saveFile(const QString &fileName) { - QFile file(fileName); - if (!file.open(QFile::WriteOnly | QFile::Text)) { - QMessageBox::warning(this, tr("SDI"), - tr("Cannot write file %1:\n%2.") - .arg(QDir::toNativeSeparators(fileName), file.errorString())); - return false; - } + QString errorMessage; - QTextStream out(&file); QGuiApplication::setOverrideCursor(Qt::WaitCursor); - out << textEdit->toPlainText(); + QSaveFile file(fileName); + if (file.open(QFile::WriteOnly | QFile::Text)) { + QTextStream out(&file); + out << textEdit->toPlainText(); + if (!file.commit()) { + errorMessage = tr("Cannot write file %1:\n%2.") + .arg(QDir::toNativeSeparators(fileName), file.errorString()); + } + } else { + errorMessage = tr("Cannot open file %1 for writing:\n%2.") + .arg(QDir::toNativeSeparators(fileName), file.errorString()); + } QGuiApplication::restoreOverrideCursor(); + if (!errorMessage.isEmpty()) { + QMessageBox::warning(this, tr("SDI"), errorMessage); + return false; + } + setCurrentFile(fileName); statusBar()->showMessage(tr("File saved"), 2000); return true; diff --git a/examples/widgets/painting/deform/pathdeform.h b/examples/widgets/painting/deform/pathdeform.h index b7c7386e2a..af869badc9 100644 --- a/examples/widgets/painting/deform/pathdeform.h +++ b/examples/widgets/painting/deform/pathdeform.h @@ -54,7 +54,7 @@ #include "arthurwidgets.h" #include <QBasicTimer> -#include <QDateTime> +#include <QElapsedTimer> #include <QPainterPath> class PathDeformRenderer : public ArthurFrame @@ -103,7 +103,7 @@ private: QBasicTimer m_repaintTimer; // QBasicTimer m_fpsTimer; // int m_fpsCounter; - QTime m_repaintTracker; + QElapsedTimer m_repaintTracker; QVector<QPainterPath> m_paths; QVector<QPointF> m_advances; diff --git a/examples/widgets/widgets/styles/norwegianwoodstyle.cpp b/examples/widgets/widgets/styles/norwegianwoodstyle.cpp index 1d7ef2637b..a178769bd8 100644 --- a/examples/widgets/widgets/styles/norwegianwoodstyle.cpp +++ b/examples/widgets/widgets/styles/norwegianwoodstyle.cpp @@ -64,9 +64,9 @@ void NorwegianWoodStyle::polish(QPalette &palette) QColor beige(236, 182, 120); QColor slightlyOpaqueBlack(0, 0, 0, 63); - QPixmap backgroundImage(":/images/woodbackground.png"); - QPixmap buttonImage(":/images/woodbutton.png"); - QPixmap midImage = buttonImage; + QImage backgroundImage(":/images/woodbackground.png"); + QImage buttonImage(":/images/woodbutton.png"); + QImage midImage = buttonImage.convertToFormat(QImage::Format_RGB32); QPainter painter; painter.begin(&midImage); @@ -311,11 +311,12 @@ void NorwegianWoodStyle::drawControl(ControlElement element, //! [37] void NorwegianWoodStyle::setTexture(QPalette &palette, QPalette::ColorRole role, //! [37] //! [38] - const QPixmap &pixmap) + const QImage &image) { for (int i = 0; i < QPalette::NColorGroups; ++i) { - QColor color = palette.brush(QPalette::ColorGroup(i), role).color(); - palette.setBrush(QPalette::ColorGroup(i), role, QBrush(color, pixmap)); + QBrush brush(image); + brush.setColor(palette.brush(QPalette::ColorGroup(i), role).color()); + palette.setBrush(QPalette::ColorGroup(i), role, brush); } } //! [38] diff --git a/examples/widgets/widgets/styles/norwegianwoodstyle.h b/examples/widgets/widgets/styles/norwegianwoodstyle.h index c41d81d23a..5a1783eb4d 100644 --- a/examples/widgets/widgets/styles/norwegianwoodstyle.h +++ b/examples/widgets/widgets/styles/norwegianwoodstyle.h @@ -80,7 +80,7 @@ public: private: static void setTexture(QPalette &palette, QPalette::ColorRole role, - const QPixmap &pixmap); + const QImage &image); static QPainterPath roundRectPath(const QRect &rect); }; //! [0] |