diff options
Diffstat (limited to 'examples/network')
49 files changed, 513 insertions, 449 deletions
diff --git a/examples/network/bearermonitor/bearermonitor.pro b/examples/network/bearermonitor/bearermonitor.pro index d75e021834..7d90b408e0 100644 --- a/examples/network/bearermonitor/bearermonitor.pro +++ b/examples/network/bearermonitor/bearermonitor.pro @@ -1,5 +1,6 @@ TARGET = bearermonitor QT = core gui network widgets +requires(qtConfig(treeview)) HEADERS = sessionwidget.h \ bearermonitor.h diff --git a/examples/network/broadcastreceiver/broadcastreceiver.pro b/examples/network/broadcastreceiver/broadcastreceiver.pro index edadf1c28d..5c58962f3a 100644 --- a/examples/network/broadcastreceiver/broadcastreceiver.pro +++ b/examples/network/broadcastreceiver/broadcastreceiver.pro @@ -1,4 +1,5 @@ QT += network widgets +requires(qtConfig(udpsocket)) HEADERS = receiver.h SOURCES = receiver.cpp \ diff --git a/examples/network/broadcastreceiver/receiver.cpp b/examples/network/broadcastreceiver/receiver.cpp index 4225a19746..2f111b4795 100644 --- a/examples/network/broadcastreceiver/receiver.cpp +++ b/examples/network/broadcastreceiver/receiver.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -59,7 +59,7 @@ Receiver::Receiver(QWidget *parent) statusLabel = new QLabel(tr("Listening for broadcasted messages")); statusLabel->setWordWrap(true); - quitButton = new QPushButton(tr("&Quit")); + auto quitButton = new QPushButton(tr("&Quit")); //! [0] udpSocket = new QUdpSocket(this); @@ -72,12 +72,12 @@ Receiver::Receiver(QWidget *parent) //! [1] connect(quitButton, SIGNAL(clicked()), this, SLOT(close())); - QHBoxLayout *buttonLayout = new QHBoxLayout; + auto buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(quitButton); buttonLayout->addStretch(1); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto mainLayout = new QVBoxLayout; mainLayout->addWidget(statusLabel); mainLayout->addLayout(buttonLayout); setLayout(mainLayout); @@ -87,13 +87,13 @@ Receiver::Receiver(QWidget *parent) void Receiver::processPendingDatagrams() { + QByteArray datagram; //! [2] while (udpSocket->hasPendingDatagrams()) { - QByteArray datagram; - datagram.resize(udpSocket->pendingDatagramSize()); + datagram.resize(int(udpSocket->pendingDatagramSize())); udpSocket->readDatagram(datagram.data(), datagram.size()); statusLabel->setText(tr("Received datagram: \"%1\"") - .arg(datagram.data())); + .arg(datagram.constData())); } //! [2] } diff --git a/examples/network/broadcastreceiver/receiver.h b/examples/network/broadcastreceiver/receiver.h index 71b91246fc..e6f8d97c23 100644 --- a/examples/network/broadcastreceiver/receiver.h +++ b/examples/network/broadcastreceiver/receiver.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -55,9 +55,7 @@ QT_BEGIN_NAMESPACE class QLabel; -class QPushButton; class QUdpSocket; -class QAction; QT_END_NAMESPACE class Receiver : public QWidget @@ -65,15 +63,14 @@ class Receiver : public QWidget Q_OBJECT public: - Receiver(QWidget *parent = 0); + explicit Receiver(QWidget *parent = nullptr); private slots: void processPendingDatagrams(); private: - QLabel *statusLabel; - QPushButton *quitButton; - QUdpSocket *udpSocket; + QLabel *statusLabel = nullptr; + QUdpSocket *udpSocket = nullptr; }; #endif diff --git a/examples/network/broadcastsender/broadcastsender.pro b/examples/network/broadcastsender/broadcastsender.pro index 4c5af7f849..9598a2e428 100644 --- a/examples/network/broadcastsender/broadcastsender.pro +++ b/examples/network/broadcastsender/broadcastsender.pro @@ -1,4 +1,5 @@ QT += network widgets +requires(qtConfig(udpsocket)) HEADERS = sender.h SOURCES = sender.cpp \ diff --git a/examples/network/broadcastsender/sender.cpp b/examples/network/broadcastsender/sender.cpp index 344f898683..ee4896e9dd 100644 --- a/examples/network/broadcastsender/sender.cpp +++ b/examples/network/broadcastsender/sender.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -50,6 +50,7 @@ #include <QtWidgets> #include <QtNetwork> +#include <QtCore> #include "sender.h" @@ -60,23 +61,21 @@ Sender::Sender(QWidget *parent) statusLabel->setWordWrap(true); startButton = new QPushButton(tr("&Start")); - quitButton = new QPushButton(tr("&Quit")); + auto quitButton = new QPushButton(tr("&Quit")); - buttonBox = new QDialogButtonBox; + auto buttonBox = new QDialogButtonBox; buttonBox->addButton(startButton, QDialogButtonBox::ActionRole); buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole); - timer = new QTimer(this); //! [0] udpSocket = new QUdpSocket(this); //! [0] - messageNo = 1; - connect(startButton, SIGNAL(clicked()), this, SLOT(startBroadcasting())); - connect(quitButton, SIGNAL(clicked()), this, SLOT(close())); - connect(timer, SIGNAL(timeout()), this, SLOT(broadcastDatagram())); + connect(startButton, &QPushButton::clicked, this, &Sender::startBroadcasting); + connect(quitButton, &QPushButton::clicked, this, &Sender::close); + connect(&timer, &QTimer::timeout, this, &Sender::broadcastDatagram); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto mainLayout = new QVBoxLayout; mainLayout->addWidget(statusLabel); mainLayout->addWidget(buttonBox); setLayout(mainLayout); @@ -87,7 +86,7 @@ Sender::Sender(QWidget *parent) void Sender::startBroadcasting() { startButton->setEnabled(false); - timer->start(1000); + timer.start(1000); } void Sender::broadcastDatagram() @@ -95,8 +94,7 @@ void Sender::broadcastDatagram() statusLabel->setText(tr("Now broadcasting datagram %1").arg(messageNo)); //! [1] QByteArray datagram = "Broadcast message " + QByteArray::number(messageNo); - udpSocket->writeDatagram(datagram.data(), datagram.size(), - QHostAddress::Broadcast, 45454); + udpSocket->writeDatagram(datagram, QHostAddress::Broadcast, 45454); //! [1] ++messageNo; } diff --git a/examples/network/broadcastsender/sender.h b/examples/network/broadcastsender/sender.h index e9c1076dd3..f91c7769ec 100644 --- a/examples/network/broadcastsender/sender.h +++ b/examples/network/broadcastsender/sender.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -52,12 +52,11 @@ #define SENDER_H #include <QWidget> +#include <QTimer> QT_BEGIN_NAMESPACE -class QDialogButtonBox; class QLabel; class QPushButton; -class QTimer; class QUdpSocket; QT_END_NAMESPACE @@ -66,20 +65,18 @@ class Sender : public QWidget Q_OBJECT public: - Sender(QWidget *parent = 0); + explicit Sender(QWidget *parent = nullptr); private slots: void startBroadcasting(); void broadcastDatagram(); private: - QLabel *statusLabel; - QPushButton *startButton; - QPushButton *quitButton; - QDialogButtonBox *buttonBox; - QUdpSocket *udpSocket; - QTimer *timer; - int messageNo; + QLabel *statusLabel = nullptr; + QPushButton *startButton = nullptr; + QUdpSocket *udpSocket = nullptr; + QTimer timer; + int messageNo = 1; }; #endif diff --git a/examples/network/doc/images/http-example.png b/examples/network/doc/images/http-example.png Binary files differindex 16b0539b1b..c5f3ef1649 100644 --- a/examples/network/doc/images/http-example.png +++ b/examples/network/doc/images/http-example.png diff --git a/examples/network/download/main.cpp b/examples/network/download/main.cpp index e5ad050de3..96111983ea 100644 --- a/examples/network/download/main.cpp +++ b/examples/network/download/main.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -48,37 +48,29 @@ ** ****************************************************************************/ -#include <QCoreApplication> -#include <QFile> -#include <QFileInfo> -#include <QList> -#include <QNetworkAccessManager> -#include <QNetworkRequest> -#include <QNetworkReply> -#include <QSslError> -#include <QStringList> -#include <QTimer> -#include <QUrl> +#include <QtCore> +#include <QtNetwork> -#include <stdio.h> +#include <cstdio> QT_BEGIN_NAMESPACE class QSslError; QT_END_NAMESPACE -QT_USE_NAMESPACE +using namespace std; class DownloadManager: public QObject { Q_OBJECT QNetworkAccessManager manager; - QList<QNetworkReply *> currentDownloads; + QVector<QNetworkReply *> currentDownloads; public: DownloadManager(); void doDownload(const QUrl &url); - QString saveFileName(const QUrl &url); + static QString saveFileName(const QUrl &url); bool saveToDisk(const QString &filename, QIODevice *data); + static bool isHttpRedirect(QNetworkReply *reply); public slots: void execute(); @@ -97,8 +89,9 @@ void DownloadManager::doDownload(const QUrl &url) QNetworkRequest request(url); QNetworkReply *reply = manager.get(request); -#ifndef QT_NO_SSL - connect(reply, SIGNAL(sslErrors(QList<QSslError>)), SLOT(sslErrors(QList<QSslError>))); +#if QT_CONFIG(ssl) + connect(reply, SIGNAL(sslErrors(QList<QSslError>)), + SLOT(sslErrors(QList<QSslError>))); #endif currentDownloads.append(reply); @@ -141,6 +134,13 @@ bool DownloadManager::saveToDisk(const QString &filename, QIODevice *data) return true; } +bool DownloadManager::isHttpRedirect(QNetworkReply *reply) +{ + int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + return statusCode == 301 || statusCode == 302 || statusCode == 303 + || statusCode == 305 || statusCode == 307 || statusCode == 308; +} + void DownloadManager::execute() { QStringList args = QCoreApplication::instance()->arguments(); @@ -156,7 +156,7 @@ void DownloadManager::execute() return; } - foreach (QString arg, args) { + for (const QString &arg : qAsConst(args)) { QUrl url = QUrl::fromEncoded(arg.toLocal8Bit()); doDownload(url); } @@ -164,8 +164,8 @@ void DownloadManager::execute() void DownloadManager::sslErrors(const QList<QSslError> &sslErrors) { -#ifndef QT_NO_SSL - foreach (const QSslError &error, sslErrors) +#if QT_CONFIG(ssl) + for (const QSslError &error : sslErrors) fprintf(stderr, "SSL error: %s\n", qPrintable(error.errorString())); #else Q_UNUSED(sslErrors); @@ -180,18 +180,24 @@ void DownloadManager::downloadFinished(QNetworkReply *reply) url.toEncoded().constData(), qPrintable(reply->errorString())); } else { - QString filename = saveFileName(url); - if (saveToDisk(filename, reply)) - printf("Download of %s succeeded (saved to %s)\n", - url.toEncoded().constData(), qPrintable(filename)); + if (isHttpRedirect(reply)) { + fputs("Request was redirected.\n", stderr); + } else { + QString filename = saveFileName(url); + if (saveToDisk(filename, reply)) { + printf("Download of %s succeeded (saved to %s)\n", + url.toEncoded().constData(), qPrintable(filename)); + } + } } currentDownloads.removeAll(reply); reply->deleteLater(); - if (currentDownloads.isEmpty()) + if (currentDownloads.isEmpty()) { // all downloads finished QCoreApplication::instance()->quit(); + } } int main(int argc, char **argv) diff --git a/examples/network/downloadmanager/downloadmanager.cpp b/examples/network/downloadmanager/downloadmanager.cpp index 69d8fd1ebc..e820b4ff70 100644 --- a/examples/network/downloadmanager/downloadmanager.cpp +++ b/examples/network/downloadmanager/downloadmanager.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -50,23 +50,21 @@ #include "downloadmanager.h" -#include <QFileInfo> -#include <QNetworkRequest> -#include <QNetworkReply> -#include <QString> -#include <QStringList> -#include <QTimer> -#include <stdio.h> +#include <QTextStream> + +#include <cstdio> + +using namespace std; DownloadManager::DownloadManager(QObject *parent) - : QObject(parent), downloadedCount(0), totalCount(0) + : QObject(parent) { } -void DownloadManager::append(const QStringList &urlList) +void DownloadManager::append(const QStringList &urls) { - foreach (QString url, urlList) - append(QUrl::fromEncoded(url.toLocal8Bit())); + for (const QString &urlAsString : urls) + append(QUrl::fromEncoded(urlAsString.toLocal8Bit())); if (downloadQueue.isEmpty()) QTimer::singleShot(0, this, SIGNAL(finished())); @@ -167,9 +165,16 @@ void DownloadManager::downloadFinished() if (currentDownload->error()) { // download failed fprintf(stderr, "Failed: %s\n", qPrintable(currentDownload->errorString())); + output.remove(); } else { - printf("Succeeded.\n"); - ++downloadedCount; + // let's check if it was actually a redirect + if (isHttpRedirect()) { + reportRedirect(); + output.remove(); + } else { + printf("Succeeded.\n"); + ++downloadedCount; + } } currentDownload->deleteLater(); @@ -180,3 +185,28 @@ void DownloadManager::downloadReadyRead() { output.write(currentDownload->readAll()); } + +bool DownloadManager::isHttpRedirect() const +{ + int statusCode = currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + return statusCode == 301 || statusCode == 302 || statusCode == 303 + || statusCode == 305 || statusCode == 307 || statusCode == 308; +} + +void DownloadManager::reportRedirect() +{ + int statusCode = currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + QUrl requestUrl = currentDownload->request().url(); + QTextStream(stderr) << "Request: " << requestUrl.toDisplayString() + << " was redirected with code: " << statusCode + << '\n'; + + QVariant target = currentDownload->attribute(QNetworkRequest::RedirectionTargetAttribute); + if (!target.isValid()) + return; + QUrl redirectUrl = target.toUrl(); + if (redirectUrl.isRelative()) + redirectUrl = requestUrl.resolved(redirectUrl); + QTextStream(stderr) << "Redirected to: " << redirectUrl.toDisplayString() + << '\n'; +} diff --git a/examples/network/downloadmanager/downloadmanager.h b/examples/network/downloadmanager/downloadmanager.h index 550a197ef8..4bc6351ff9 100644 --- a/examples/network/downloadmanager/downloadmanager.h +++ b/examples/network/downloadmanager/downloadmanager.h @@ -51,12 +51,8 @@ #ifndef DOWNLOADMANAGER_H #define DOWNLOADMANAGER_H -#include <QFile> -#include <QObject> -#include <QQueue> -#include <QTime> -#include <QUrl> -#include <QNetworkAccessManager> +#include <QtNetwork> +#include <QtCore> #include "textprogressbar.h" @@ -64,11 +60,11 @@ class DownloadManager: public QObject { Q_OBJECT public: - DownloadManager(QObject *parent = 0); + explicit DownloadManager(QObject *parent = nullptr); void append(const QUrl &url); - void append(const QStringList &urlList); - QString saveFileName(const QUrl &url); + void append(const QStringList &urls); + static QString saveFileName(const QUrl &url); signals: void finished(); @@ -80,15 +76,18 @@ private slots: void downloadReadyRead(); private: + bool isHttpRedirect() const; + void reportRedirect(); + QNetworkAccessManager manager; QQueue<QUrl> downloadQueue; - QNetworkReply *currentDownload; + QNetworkReply *currentDownload = nullptr; QFile output; QTime downloadTime; TextProgressBar progressBar; - int downloadedCount; - int totalCount; + int downloadedCount = 0; + int totalCount = 0; }; #endif diff --git a/examples/network/downloadmanager/main.cpp b/examples/network/downloadmanager/main.cpp index 158f04c9e6..e3ba490992 100644 --- a/examples/network/downloadmanager/main.cpp +++ b/examples/network/downloadmanager/main.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -50,11 +50,15 @@ #include <QCoreApplication> #include <QStringList> + #include "downloadmanager.h" -#include <stdio.h> + +#include <cstdio> int main(int argc, char **argv) { + using namespace std; + QCoreApplication app(argc, argv); QStringList arguments = app.arguments(); arguments.takeFirst(); // remove the first argument, which is the program's name diff --git a/examples/network/downloadmanager/textprogressbar.cpp b/examples/network/downloadmanager/textprogressbar.cpp index d9506a563a..3449e6bad5 100644 --- a/examples/network/downloadmanager/textprogressbar.cpp +++ b/examples/network/downloadmanager/textprogressbar.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -49,22 +49,21 @@ ****************************************************************************/ #include "textprogressbar.h" + #include <QByteArray> -#include <stdio.h> -TextProgressBar::TextProgressBar() - : value(0), maximum(-1), iteration(0) -{ -} +#include <cstdio> + +using namespace std; void TextProgressBar::clear() { printf("\n"); fflush(stdout); - iteration = 0; value = 0; maximum = -1; + iteration = 0; } void TextProgressBar::update() diff --git a/examples/network/downloadmanager/textprogressbar.h b/examples/network/downloadmanager/textprogressbar.h index 57bcd6e92a..30affeb55c 100644 --- a/examples/network/downloadmanager/textprogressbar.h +++ b/examples/network/downloadmanager/textprogressbar.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -56,8 +56,6 @@ class TextProgressBar { public: - TextProgressBar(); - void clear(); void update(); void setMessage(const QString &message); @@ -65,9 +63,9 @@ public: private: QString message; - qint64 value; - qint64 maximum; - int iteration; + qint64 value = 0; + qint64 maximum = -1; + int iteration = 0; }; #endif diff --git a/examples/network/fortuneclient/client.cpp b/examples/network/fortuneclient/client.cpp index c0043e246f..4d3a318a7b 100644 --- a/examples/network/fortuneclient/client.cpp +++ b/examples/network/fortuneclient/client.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -60,7 +60,6 @@ Client::Client(QWidget *parent) , portLineEdit(new QLineEdit) , getFortuneButton(new QPushButton(tr("Get Fortune"))) , tcpSocket(new QTcpSocket(this)) - , networkSession(Q_NULLPTR) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); //! [0] @@ -90,9 +89,9 @@ Client::Client(QWidget *parent) portLineEdit->setValidator(new QIntValidator(1, 65535, this)); - QLabel *hostLabel = new QLabel(tr("&Server name:")); + auto hostLabel = new QLabel(tr("&Server name:")); hostLabel->setBuddy(hostCombo); - QLabel *portLabel = new QLabel(tr("S&erver port:")); + auto portLabel = new QLabel(tr("S&erver port:")); portLabel->setBuddy(portLineEdit); statusLabel = new QLabel(tr("This examples requires that you run the " @@ -101,9 +100,9 @@ Client::Client(QWidget *parent) getFortuneButton->setDefault(true); getFortuneButton->setEnabled(false); - QPushButton *quitButton = new QPushButton(tr("Quit")); + auto quitButton = new QPushButton(tr("Quit")); - QDialogButtonBox *buttonBox = new QDialogButtonBox; + auto buttonBox = new QDialogButtonBox; buttonBox->addButton(getFortuneButton, QDialogButtonBox::ActionRole); buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole); @@ -127,13 +126,13 @@ Client::Client(QWidget *parent) this, &Client::displayError); //! [4] - QGridLayout *mainLayout = Q_NULLPTR; + QGridLayout *mainLayout = nullptr; if (QGuiApplication::styleHints()->showIsFullScreen() || QGuiApplication::styleHints()->showIsMaximized()) { - QVBoxLayout *outerVerticalLayout = new QVBoxLayout(this); + auto outerVerticalLayout = new QVBoxLayout(this); outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding)); - QHBoxLayout *outerHorizontalLayout = new QHBoxLayout; + auto outerHorizontalLayout = new QHBoxLayout; outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored)); - QGroupBox *groupBox = new QGroupBox(QGuiApplication::applicationDisplayName()); + auto groupBox = new QGroupBox(QGuiApplication::applicationDisplayName()); mainLayout = new QGridLayout(groupBox); outerHorizontalLayout->addWidget(groupBox); outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored)); diff --git a/examples/network/fortuneclient/client.h b/examples/network/fortuneclient/client.h index 8037e9b047..ac335acb83 100644 --- a/examples/network/fortuneclient/client.h +++ b/examples/network/fortuneclient/client.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -51,9 +51,9 @@ #ifndef CLIENT_H #define CLIENT_H +#include <QDataStream> #include <QDialog> #include <QTcpSocket> -#include <QDataStream> QT_BEGIN_NAMESPACE class QComboBox; @@ -70,7 +70,7 @@ class Client : public QDialog Q_OBJECT public: - explicit Client(QWidget *parent = Q_NULLPTR); + explicit Client(QWidget *parent = nullptr); private slots: void requestNewFortune(); @@ -80,16 +80,16 @@ private slots: void sessionOpened(); private: - QComboBox *hostCombo; - QLineEdit *portLineEdit; - QLabel *statusLabel; - QPushButton *getFortuneButton; + QComboBox *hostCombo = nullptr; + QLineEdit *portLineEdit = nullptr; + QLabel *statusLabel = nullptr; + QPushButton *getFortuneButton = nullptr; - QTcpSocket *tcpSocket; + QTcpSocket *tcpSocket = nullptr; QDataStream in; QString currentFortune; - QNetworkSession *networkSession; + QNetworkSession *networkSession = nullptr; }; //! [0] diff --git a/examples/network/fortuneclient/fortuneclient.pro b/examples/network/fortuneclient/fortuneclient.pro index 8b376d9c53..6cf04a8b62 100644 --- a/examples/network/fortuneclient/fortuneclient.pro +++ b/examples/network/fortuneclient/fortuneclient.pro @@ -1,4 +1,5 @@ QT += network widgets +requires(qtConfig(combobox)) HEADERS = client.h SOURCES = client.cpp \ diff --git a/examples/network/fortuneclient/main.cpp b/examples/network/fortuneclient/main.cpp index e313b251ef..6b02708ce1 100644 --- a/examples/network/fortuneclient/main.cpp +++ b/examples/network/fortuneclient/main.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -54,7 +54,7 @@ int main(int argc, char *argv[]) { QApplication app(argc, argv); - QGuiApplication::setApplicationDisplayName(Client::tr("Fortune Client")); + QApplication::setApplicationDisplayName(Client::tr("Fortune Client")); Client client; client.show(); return app.exec(); diff --git a/examples/network/fortuneserver/main.cpp b/examples/network/fortuneserver/main.cpp index 12137d647c..a64fcb26dc 100644 --- a/examples/network/fortuneserver/main.cpp +++ b/examples/network/fortuneserver/main.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -49,18 +49,14 @@ ****************************************************************************/ #include <QApplication> -#include <QtCore> - -#include <stdlib.h> #include "server.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); - QGuiApplication::setApplicationDisplayName(Server::tr("Fortune Server")); + QApplication::setApplicationDisplayName(Server::tr("Fortune Server")); Server server; server.show(); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); return app.exec(); } diff --git a/examples/network/fortuneserver/server.cpp b/examples/network/fortuneserver/server.cpp index f027d68dd9..7db81fe07a 100644 --- a/examples/network/fortuneserver/server.cpp +++ b/examples/network/fortuneserver/server.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -50,16 +50,13 @@ #include <QtWidgets> #include <QtNetwork> - -#include <stdlib.h> +#include <QtCore> #include "server.h" Server::Server(QWidget *parent) : QDialog(parent) , statusLabel(new QLabel) - , tcpServer(Q_NULLPTR) - , networkSession(0) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); statusLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); @@ -89,46 +86,46 @@ Server::Server(QWidget *parent) } //! [2] - fortunes << tr("You've been leading a dog's life. Stay off the furniture.") - << tr("You've got to think about tomorrow.") - << tr("You will be surprised by a loud noise.") - << tr("You will feel hungry again in another hour.") - << tr("You might have mail.") - << tr("You cannot kill time without injuring eternity.") - << tr("Computers are not intelligent. They only think they are."); + fortunes << tr("You've been leading a dog's life. Stay off the furniture.") + << tr("You've got to think about tomorrow.") + << tr("You will be surprised by a loud noise.") + << tr("You will feel hungry again in another hour.") + << tr("You might have mail.") + << tr("You cannot kill time without injuring eternity.") + << tr("Computers are not intelligent. They only think they are."); //! [2] - QPushButton *quitButton = new QPushButton(tr("Quit")); - quitButton->setAutoDefault(false); - connect(quitButton, &QAbstractButton::clicked, this, &QWidget::close); + auto quitButton = new QPushButton(tr("Quit")); + quitButton->setAutoDefault(false); + connect(quitButton, &QAbstractButton::clicked, this, &QWidget::close); //! [3] - connect(tcpServer, &QTcpServer::newConnection, this, &Server::sendFortune); + connect(tcpServer, &QTcpServer::newConnection, this, &Server::sendFortune); //! [3] - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->addStretch(1); - buttonLayout->addWidget(quitButton); - buttonLayout->addStretch(1); - - QVBoxLayout *mainLayout = Q_NULLPTR; - if (QGuiApplication::styleHints()->showIsFullScreen() || QGuiApplication::styleHints()->showIsMaximized()) { - QVBoxLayout *outerVerticalLayout = new QVBoxLayout(this); - outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding)); - QHBoxLayout *outerHorizontalLayout = new QHBoxLayout; - outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored)); - QGroupBox *groupBox = new QGroupBox(QGuiApplication::applicationDisplayName()); - mainLayout = new QVBoxLayout(groupBox); - outerHorizontalLayout->addWidget(groupBox); - outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored)); - outerVerticalLayout->addLayout(outerHorizontalLayout); - outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding)); - } else { - mainLayout = new QVBoxLayout(this); - } + auto buttonLayout = new QHBoxLayout; + buttonLayout->addStretch(1); + buttonLayout->addWidget(quitButton); + buttonLayout->addStretch(1); + + QVBoxLayout *mainLayout = nullptr; + if (QGuiApplication::styleHints()->showIsFullScreen() || QGuiApplication::styleHints()->showIsMaximized()) { + auto outerVerticalLayout = new QVBoxLayout(this); + outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding)); + auto outerHorizontalLayout = new QHBoxLayout; + outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored)); + auto groupBox = new QGroupBox(QGuiApplication::applicationDisplayName()); + mainLayout = new QVBoxLayout(groupBox); + outerHorizontalLayout->addWidget(groupBox); + outerHorizontalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored)); + outerVerticalLayout->addLayout(outerHorizontalLayout); + outerVerticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding)); + } else { + mainLayout = new QVBoxLayout(this); + } - mainLayout->addWidget(statusLabel); - mainLayout->addLayout(buttonLayout); + mainLayout->addWidget(statusLabel); + mainLayout->addLayout(buttonLayout); - setWindowTitle(QGuiApplication::applicationDisplayName()); + setWindowTitle(QGuiApplication::applicationDisplayName()); } void Server::sessionOpened() @@ -183,9 +180,9 @@ void Server::sendFortune() //! [5] QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); - out.setVersion(QDataStream::Qt_4_0); + out.setVersion(QDataStream::Qt_5_10); - out << fortunes.at(qrand() % fortunes.size()); + out << fortunes[QRandomGenerator::global()->bounded(fortunes.size())]; //! [4] //! [7] QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); diff --git a/examples/network/fortuneserver/server.h b/examples/network/fortuneserver/server.h index ea5ed78292..c5bfa7d928 100644 --- a/examples/network/fortuneserver/server.h +++ b/examples/network/fortuneserver/server.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -52,10 +52,11 @@ #define SERVER_H #include <QDialog> +#include <QString> +#include <QVector> QT_BEGIN_NAMESPACE class QLabel; -class QPushButton; class QTcpServer; class QNetworkSession; QT_END_NAMESPACE @@ -66,17 +67,17 @@ class Server : public QDialog Q_OBJECT public: - explicit Server(QWidget *parent = Q_NULLPTR); + explicit Server(QWidget *parent = nullptr); private slots: void sessionOpened(); void sendFortune(); private: - QLabel *statusLabel; - QTcpServer *tcpServer; - QStringList fortunes; - QNetworkSession *networkSession; + QLabel *statusLabel = nullptr; + QTcpServer *tcpServer = nullptr; + QVector<QString> fortunes; + QNetworkSession *networkSession = nullptr; }; //! [0] diff --git a/examples/network/googlesuggest/googlesuggest.cpp b/examples/network/googlesuggest/googlesuggest.cpp index 9fdfd8faa6..24fdde0a5c 100644 --- a/examples/network/googlesuggest/googlesuggest.cpp +++ b/examples/network/googlesuggest/googlesuggest.cpp @@ -51,7 +51,7 @@ //! [1] #include "googlesuggest.h" -#define GSUGGEST_URL "http://google.com/complete/search?output=toolbar&q=%1" +const QString gsuggestUrl(QStringLiteral("http://google.com/complete/search?output=toolbar&q=%1")); //! [1] //! [2] @@ -77,11 +77,10 @@ GSuggestCompletion::GSuggestCompletion(QLineEdit *parent): QObject(parent), edit connect(popup, SIGNAL(itemClicked(QTreeWidgetItem*,int)), SLOT(doneCompletion())); - timer = new QTimer(this); - timer->setSingleShot(true); - timer->setInterval(500); - connect(timer, SIGNAL(timeout()), SLOT(autoSuggest())); - connect(editor, SIGNAL(textEdited(QString)), timer, SLOT(start())); + timer.setSingleShot(true); + timer.setInterval(500); + connect(&timer, SIGNAL(timeout()), SLOT(autoSuggest())); + connect(editor, SIGNAL(textEdited(QString)), &timer, SLOT(start())); connect(&networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleNetworkData(QNetworkReply*))); @@ -109,7 +108,6 @@ bool GSuggestCompletion::eventFilter(QObject *obj, QEvent *ev) } if (ev->type() == QEvent::KeyPress) { - bool consumed = false; int key = static_cast<QKeyEvent*>(ev)->key(); switch (key) { @@ -148,9 +146,8 @@ bool GSuggestCompletion::eventFilter(QObject *obj, QEvent *ev) //! [4] //! [5] -void GSuggestCompletion::showCompletion(const QStringList &choices) +void GSuggestCompletion::showCompletion(const QVector<QString> &choices) { - if (choices.isEmpty()) return; @@ -159,12 +156,13 @@ void GSuggestCompletion::showCompletion(const QStringList &choices) popup->setUpdatesEnabled(false); popup->clear(); - for (int i = 0; i < choices.count(); ++i) { - QTreeWidgetItem * item; - item = new QTreeWidgetItem(popup); - item->setText(0, choices[i]); + + for (const auto &choice : choices) { + auto item = new QTreeWidgetItem(popup); + item->setText(0, choice); item->setTextColor(0, color); } + popup->setCurrentItem(popup->topLevelItem(0)); popup->resizeColumnToContents(0); popup->setUpdatesEnabled(true); @@ -178,7 +176,7 @@ void GSuggestCompletion::showCompletion(const QStringList &choices) //! [6] void GSuggestCompletion::doneCompletion() { - timer->stop(); + timer.stop(); popup->hide(); editor->setFocus(); QTreeWidgetItem *item = popup->currentItem(); @@ -193,15 +191,15 @@ void GSuggestCompletion::doneCompletion() void GSuggestCompletion::autoSuggest() { QString str = editor->text(); - QString url = QString(GSUGGEST_URL).arg(str); - networkManager.get(QNetworkRequest(QString(url))); + QString url = gsuggestUrl.arg(str); + networkManager.get(QNetworkRequest(url)); } //! [7] //! [8] void GSuggestCompletion::preventSuggest() { - timer->stop(); + timer.stop(); } //! [8] @@ -209,8 +207,8 @@ void GSuggestCompletion::preventSuggest() void GSuggestCompletion::handleNetworkData(QNetworkReply *networkReply) { QUrl url = networkReply->url(); - if (!networkReply->error()) { - QStringList choices; + if (networkReply->error() == QNetworkReply::NoError) { + QVector<QString> choices; QByteArray response(networkReply->readAll()); QXmlStreamReader xml(response); diff --git a/examples/network/googlesuggest/googlesuggest.h b/examples/network/googlesuggest/googlesuggest.h index 1d42f31571..a0b0ac069c 100644 --- a/examples/network/googlesuggest/googlesuggest.h +++ b/examples/network/googlesuggest/googlesuggest.h @@ -53,14 +53,7 @@ #include <QtWidgets> #include <QtNetwork> -#include <QObject> - -QT_BEGIN_NAMESPACE -class QLineEdit; -class QNetworkReply; -class QTimer; -class QTreeWidget; -QT_END_NAMESPACE +#include <QtCore> //! [1] class GSuggestCompletion : public QObject @@ -68,10 +61,10 @@ class GSuggestCompletion : public QObject Q_OBJECT public: - GSuggestCompletion(QLineEdit *parent = 0); + explicit GSuggestCompletion(QLineEdit *parent = nullptr); ~GSuggestCompletion(); bool eventFilter(QObject *obj, QEvent *ev) override; - void showCompletion(const QStringList &choices); + void showCompletion(const QVector<QString> &choices); public slots: @@ -81,9 +74,9 @@ public slots: void handleNetworkData(QNetworkReply *networkReply); private: - QLineEdit *editor; - QTreeWidget *popup; - QTimer *timer; + QLineEdit *editor = nullptr; + QTreeWidget *popup = nullptr; + QTimer timer; QNetworkAccessManager networkManager; }; //! [1] diff --git a/examples/network/googlesuggest/googlesuggest.pro b/examples/network/googlesuggest/googlesuggest.pro index 84db77e30b..6e73906303 100644 --- a/examples/network/googlesuggest/googlesuggest.pro +++ b/examples/network/googlesuggest/googlesuggest.pro @@ -1,4 +1,5 @@ QT += network widgets +requires(qtConfig(itemviews)) SOURCES = main.cpp searchbox.cpp googlesuggest.cpp HEADERS = searchbox.h googlesuggest.h diff --git a/examples/network/googlesuggest/main.cpp b/examples/network/googlesuggest/main.cpp index 9de966d7a5..ab819c5502 100644 --- a/examples/network/googlesuggest/main.cpp +++ b/examples/network/googlesuggest/main.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -55,7 +55,7 @@ int main(int argc, char * argv[]) { QApplication app(argc, argv); - SearchBox *searchEdit = new SearchBox; - searchEdit->show(); + SearchBox searchEdit; + searchEdit.show(); return app.exec(); } diff --git a/examples/network/googlesuggest/searchbox.cpp b/examples/network/googlesuggest/searchbox.cpp index e0754a7de2..d0bdb70daa 100644 --- a/examples/network/googlesuggest/searchbox.cpp +++ b/examples/network/googlesuggest/searchbox.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -54,7 +54,7 @@ #include "searchbox.h" #include "googlesuggest.h" -#define GSEARCH_URL "http://www.google.com/search?q=%1" +const QString gsearchUrl = QStringLiteral("http://www.google.com/search?q=%1"); //! [1] SearchBox::SearchBox(QWidget *parent): QLineEdit(parent) @@ -75,8 +75,8 @@ SearchBox::SearchBox(QWidget *parent): QLineEdit(parent) void SearchBox::doSearch() { completer->preventSuggest(); - QString url = QString(GSEARCH_URL).arg(text()); - QDesktopServices::openUrl(QUrl(url)); + QString url = gsearchUrl.arg(text()); + QDesktopServices::openUrl(url); } //! [2] diff --git a/examples/network/googlesuggest/searchbox.h b/examples/network/googlesuggest/searchbox.h index eea5854de8..fbd33011b7 100644 --- a/examples/network/googlesuggest/searchbox.h +++ b/examples/network/googlesuggest/searchbox.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -61,13 +61,13 @@ class SearchBox: public QLineEdit Q_OBJECT public: - SearchBox(QWidget *parent = 0); + explicit SearchBox(QWidget *parent = nullptr); protected slots: void doSearch(); private: - GSuggestCompletion *completer; + GSuggestCompletion *completer = nullptr; //! [1] }; diff --git a/examples/network/http/httpwindow.cpp b/examples/network/http/httpwindow.cpp index fddd2c809a..ec90b8f7fe 100644 --- a/examples/network/http/httpwindow.cpp +++ b/examples/network/http/httpwindow.cpp @@ -55,12 +55,12 @@ #include "httpwindow.h" #include "ui_authenticationdialog.h" -#ifndef QT_NO_SSL -static const char defaultUrl[] = "https://www.qt.io/"; +#if QT_CONFIG(ssl) +const char defaultUrl[] = "https://www.qt.io/"; #else -static const char defaultUrl[] = "http://www.qt.io/"; +const char defaultUrl[] = "http://www.qt.io/"; #endif -static const char defaultFileName[] = "index.html"; +const char defaultFileName[] = "index.html"; ProgressDialog::ProgressDialog(const QUrl &url, QWidget *parent) : QProgressDialog(parent) @@ -71,6 +71,7 @@ ProgressDialog::ProgressDialog(const QUrl &url, QWidget *parent) setMinimum(0); setValue(0); setMinimumDuration(0); + setMinimumSize(QSize(400, 75)); } void ProgressDialog::networkReplyProgress(qint64 bytesRead, qint64 totalBytes) @@ -87,8 +88,8 @@ HttpWindow::HttpWindow(QWidget *parent) , launchCheckBox(new QCheckBox("Launch file")) , defaultFileLineEdit(new QLineEdit(defaultFileName)) , downloadDirectoryLineEdit(new QLineEdit) - , reply(Q_NULLPTR) - , file(Q_NULLPTR) + , reply(nullptr) + , file(nullptr) , httpRequestAborted(false) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); @@ -174,15 +175,22 @@ void HttpWindow::downloadFile() if (fileName.isEmpty()) fileName = defaultFileName; QString downloadDirectory = QDir::cleanPath(downloadDirectoryLineEdit->text().trimmed()); - if (!downloadDirectory.isEmpty() && QFileInfo(downloadDirectory).isDir()) + bool useDirectory = !downloadDirectory.isEmpty() && QFileInfo(downloadDirectory).isDir(); + if (useDirectory) fileName.prepend(downloadDirectory + '/'); if (QFile::exists(fileName)) { if (QMessageBox::question(this, tr("Overwrite Existing File"), - tr("There already exists a file called %1 in " - "the current directory. Overwrite?").arg(fileName), - QMessageBox::Yes|QMessageBox::No, QMessageBox::No) - == QMessageBox::No) + tr("There already exists a file called %1%2." + " Overwrite?") + .arg(fileName, + useDirectory + ? QString() + : QStringLiteral(" in the current directory")), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No) + == QMessageBox::No) { return; + } QFile::remove(fileName); } @@ -204,7 +212,7 @@ QFile *HttpWindow::openFileForWrite(const QString &fileName) tr("Unable to save the file %1: %2.") .arg(QDir::toNativeSeparators(fileName), file->errorString())); - return Q_NULLPTR; + return nullptr; } return file.take(); } @@ -224,12 +232,12 @@ void HttpWindow::httpFinished() fi.setFile(file->fileName()); file->close(); delete file; - file = Q_NULLPTR; + file = nullptr; } if (httpRequestAborted) { reply->deleteLater(); - reply = Q_NULLPTR; + reply = nullptr; return; } @@ -238,21 +246,23 @@ void HttpWindow::httpFinished() statusLabel->setText(tr("Download failed:\n%1.").arg(reply->errorString())); downloadButton->setEnabled(true); reply->deleteLater(); - reply = Q_NULLPTR; + reply = nullptr; return; } const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); reply->deleteLater(); - reply = Q_NULLPTR; + reply = nullptr; if (!redirectionTarget.isNull()) { const QUrl redirectedUrl = url.resolved(redirectionTarget.toUrl()); if (QMessageBox::question(this, tr("Redirect"), tr("Redirect to %1 ?").arg(redirectedUrl.toString()), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { + QFile::remove(fi.absoluteFilePath()); downloadButton->setEnabled(true); + statusLabel->setText(tr("Download failed:\nRedirect rejected.")); return; } file = openFileForWrite(fi.absoluteFilePath()); @@ -286,7 +296,7 @@ void HttpWindow::enableDownloadButton() downloadButton->setEnabled(!urlLineEdit->text().isEmpty()); } -void HttpWindow::slotAuthenticationRequired(QNetworkReply*,QAuthenticator *authenticator) +void HttpWindow::slotAuthenticationRequired(QNetworkReply *, QAuthenticator *authenticator) { QDialog authenticationDialog; Ui::Dialog ui; @@ -306,7 +316,7 @@ void HttpWindow::slotAuthenticationRequired(QNetworkReply*,QAuthenticator *authe } #ifndef QT_NO_SSL -void HttpWindow::sslErrors(QNetworkReply*,const QList<QSslError> &errors) +void HttpWindow::sslErrors(QNetworkReply *, const QList<QSslError> &errors) { QString errorString; foreach (const QSslError &error, errors) { diff --git a/examples/network/http/httpwindow.h b/examples/network/http/httpwindow.h index 3bb43dbf89..20ad2bb4da 100644 --- a/examples/network/http/httpwindow.h +++ b/examples/network/http/httpwindow.h @@ -71,7 +71,7 @@ class ProgressDialog : public QProgressDialog { Q_OBJECT public: - explicit ProgressDialog(const QUrl &url, QWidget *parent = Q_NULLPTR); + explicit ProgressDialog(const QUrl &url, QWidget *parent = nullptr); public slots: void networkReplyProgress(qint64 bytesRead, qint64 totalBytes); @@ -82,7 +82,7 @@ class HttpWindow : public QDialog Q_OBJECT public: - explicit HttpWindow(QWidget *parent = Q_NULLPTR); + explicit HttpWindow(QWidget *parent = nullptr); void startRequest(const QUrl &requestedUrl); @@ -92,9 +92,9 @@ private slots: void httpFinished(); void httpReadyRead(); void enableDownloadButton(); - void slotAuthenticationRequired(QNetworkReply*,QAuthenticator *); + void slotAuthenticationRequired(QNetworkReply *, QAuthenticator *authenticator); #ifndef QT_NO_SSL - void sslErrors(QNetworkReply*,const QList<QSslError> &errors); + void sslErrors(QNetworkReply *, const QList<QSslError> &errors); #endif private: diff --git a/examples/network/multicastreceiver/multicastreceiver.pro b/examples/network/multicastreceiver/multicastreceiver.pro index 6906fc6cb5..e9bcb45a8d 100644 --- a/examples/network/multicastreceiver/multicastreceiver.pro +++ b/examples/network/multicastreceiver/multicastreceiver.pro @@ -1,4 +1,5 @@ QT += network widgets +requires(qtConfig(udpsocket)) HEADERS = receiver.h SOURCES = receiver.cpp \ diff --git a/examples/network/multicastreceiver/receiver.cpp b/examples/network/multicastreceiver/receiver.cpp index 10154c60cc..d793242ad0 100644 --- a/examples/network/multicastreceiver/receiver.cpp +++ b/examples/network/multicastreceiver/receiver.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -54,41 +54,56 @@ #include "receiver.h" Receiver::Receiver(QWidget *parent) - : QDialog(parent) + : QDialog(parent), + groupAddress4(QStringLiteral("239.255.43.21")), + groupAddress6(QStringLiteral("ff12::2115")) { - groupAddress = QHostAddress("239.255.43.21"); + statusLabel = new QLabel(tr("Listening for multicast messages on both IPv4 and IPv6")); + auto quitButton = new QPushButton(tr("&Quit")); - statusLabel = new QLabel(tr("Listening for multicasted messages")); - quitButton = new QPushButton(tr("&Quit")); - - udpSocket = new QUdpSocket(this); - udpSocket->bind(QHostAddress::AnyIPv4, 45454, QUdpSocket::ShareAddress); - udpSocket->joinMulticastGroup(groupAddress); - - connect(udpSocket, SIGNAL(readyRead()), - this, SLOT(processPendingDatagrams())); - connect(quitButton, SIGNAL(clicked()), this, SLOT(close())); - - QHBoxLayout *buttonLayout = new QHBoxLayout; + auto buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(quitButton); buttonLayout->addStretch(1); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto mainLayout = new QVBoxLayout; mainLayout->addWidget(statusLabel); mainLayout->addLayout(buttonLayout); setLayout(mainLayout); setWindowTitle(tr("Multicast Receiver")); + + udpSocket4.bind(QHostAddress::AnyIPv4, 45454, QUdpSocket::ShareAddress); + udpSocket4.joinMulticastGroup(groupAddress4); + + if (!udpSocket6.bind(QHostAddress::AnyIPv6, 45454, QUdpSocket::ShareAddress) || + !udpSocket6.joinMulticastGroup(groupAddress6)) + statusLabel->setText(tr("Listening for multicast messages on IPv4 only")); + + connect(&udpSocket4, SIGNAL(readyRead()), + this, SLOT(processPendingDatagrams())); + connect(&udpSocket6, &QUdpSocket::readyRead, this, &Receiver::processPendingDatagrams); + connect(quitButton, SIGNAL(clicked()), this, SLOT(close())); } void Receiver::processPendingDatagrams() { - while (udpSocket->hasPendingDatagrams()) { - QByteArray datagram; - datagram.resize(udpSocket->pendingDatagramSize()); - udpSocket->readDatagram(datagram.data(), datagram.size()); - statusLabel->setText(tr("Received datagram: \"%1\"") - .arg(datagram.data())); + QByteArray datagram; + + // using QUdpSocket::readDatagram (API since Qt 4) + while (udpSocket4.hasPendingDatagrams()) { + datagram.resize(int(udpSocket4.pendingDatagramSize())); + udpSocket4.readDatagram(datagram.data(), datagram.size()); + statusLabel->setText(tr("Received IPv4 datagram: \"%1\"") + .arg(datagram.constData())); + } + + // using QUdpSocket::receiveDatagram (API since Qt 5.8) + while (udpSocket6.hasPendingDatagrams()) { + QNetworkDatagram dgram = udpSocket6.receiveDatagram(); + statusLabel->setText(statusLabel->text() + + tr("\nReceived IPv6 datagram from [%2]:%3: \"%1\"") + .arg(dgram.data().constData(), dgram.senderAddress().toString()) + .arg(dgram.senderPort())); } } diff --git a/examples/network/multicastreceiver/receiver.h b/examples/network/multicastreceiver/receiver.h index efef1cdb30..0325d861df 100644 --- a/examples/network/multicastreceiver/receiver.h +++ b/examples/network/multicastreceiver/receiver.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -53,11 +53,10 @@ #include <QDialog> #include <QHostAddress> +#include <QUdpSocket> QT_BEGIN_NAMESPACE class QLabel; -class QPushButton; -class QUdpSocket; QT_END_NAMESPACE class Receiver : public QDialog @@ -65,16 +64,17 @@ class Receiver : public QDialog Q_OBJECT public: - Receiver(QWidget *parent = 0); + explicit Receiver(QWidget *parent = nullptr); private slots: void processPendingDatagrams(); private: - QLabel *statusLabel; - QPushButton *quitButton; - QUdpSocket *udpSocket; - QHostAddress groupAddress; + QLabel *statusLabel = nullptr; + QUdpSocket udpSocket4; + QUdpSocket udpSocket6; + QHostAddress groupAddress4; + QHostAddress groupAddress6; }; #endif diff --git a/examples/network/multicastsender/multicastsender.pro b/examples/network/multicastsender/multicastsender.pro index 4797b194a9..160f37be6d 100644 --- a/examples/network/multicastsender/multicastsender.pro +++ b/examples/network/multicastsender/multicastsender.pro @@ -2,6 +2,7 @@ HEADERS = sender.h SOURCES = sender.cpp \ main.cpp QT += network widgets +requires(qtConfig(udpsocket)) # install target.path = $$[QT_INSTALL_EXAMPLES]/network/multicastsender diff --git a/examples/network/multicastsender/sender.cpp b/examples/network/multicastsender/sender.cpp index 4aa65fee27..a542a2528f 100644 --- a/examples/network/multicastsender/sender.cpp +++ b/examples/network/multicastsender/sender.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -48,43 +48,45 @@ ** ****************************************************************************/ -#include <QtWidgets> -#include <QtNetwork> - #include "sender.h" Sender::Sender(QWidget *parent) - : QDialog(parent) + : QDialog(parent), + groupAddress4(QStringLiteral("239.255.43.21")), + groupAddress6(QStringLiteral("ff12::2115")) { - groupAddress = QHostAddress("239.255.43.21"); + // force binding to their respective families + udpSocket4.bind(QHostAddress(QHostAddress::AnyIPv4), 0); + udpSocket6.bind(QHostAddress(QHostAddress::AnyIPv6), udpSocket4.localPort()); - statusLabel = new QLabel(tr("Ready to multicast datagrams to group %1 on port 45454").arg(groupAddress.toString())); + QString msg = tr("Ready to multicast datagrams to groups %1 and [%2] on port 45454").arg(groupAddress4.toString()); + if (udpSocket6.state() != QAbstractSocket::BoundState) + msg = tr("IPv6 failed. Ready to multicast datagrams to group %1 on port 45454").arg(groupAddress4.toString()); + else + msg = msg.arg(groupAddress6.toString()); + statusLabel = new QLabel(msg); - ttlLabel = new QLabel(tr("TTL for multicast datagrams:")); - ttlSpinBox = new QSpinBox; + auto ttlLabel = new QLabel(tr("TTL for IPv4 multicast datagrams:")); + auto ttlSpinBox = new QSpinBox; ttlSpinBox->setRange(0, 255); - QHBoxLayout *ttlLayout = new QHBoxLayout; + auto ttlLayout = new QHBoxLayout; ttlLayout->addWidget(ttlLabel); ttlLayout->addWidget(ttlSpinBox); startButton = new QPushButton(tr("&Start")); - quitButton = new QPushButton(tr("&Quit")); + auto quitButton = new QPushButton(tr("&Quit")); - buttonBox = new QDialogButtonBox; + auto buttonBox = new QDialogButtonBox; buttonBox->addButton(startButton, QDialogButtonBox::ActionRole); buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole); - timer = new QTimer(this); - udpSocket = new QUdpSocket(this); - messageNo = 1; - - connect(ttlSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ttlChanged(int))); - connect(startButton, SIGNAL(clicked()), this, SLOT(startSending())); - connect(quitButton, SIGNAL(clicked()), this, SLOT(close())); - connect(timer, SIGNAL(timeout()), this, SLOT(sendDatagram())); + connect(ttlSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &Sender::ttlChanged); + connect(startButton, &QPushButton::clicked, this, &Sender::startSending); + connect(quitButton, &QPushButton::clicked, this, &Sender::close); + connect(&timer, &QTimer::timeout, this, &Sender::sendDatagram); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto mainLayout = new QVBoxLayout; mainLayout->addWidget(statusLabel); mainLayout->addLayout(ttlLayout); mainLayout->addWidget(buttonBox); @@ -96,20 +98,22 @@ Sender::Sender(QWidget *parent) void Sender::ttlChanged(int newTtl) { - udpSocket->setSocketOption(QAbstractSocket::MulticastTtlOption, newTtl); + // we only set the TTL on the IPv4 socket, as that changes the multicast scope + udpSocket4.setSocketOption(QAbstractSocket::MulticastTtlOption, newTtl); } void Sender::startSending() { startButton->setEnabled(false); - timer->start(1000); + timer.start(1000); } void Sender::sendDatagram() { statusLabel->setText(tr("Now sending datagram %1").arg(messageNo)); QByteArray datagram = "Multicast message " + QByteArray::number(messageNo); - udpSocket->writeDatagram(datagram.data(), datagram.size(), - groupAddress, 45454); + udpSocket4.writeDatagram(datagram, groupAddress4, 45454); + if (udpSocket6.state() == QAbstractSocket::BoundState) + udpSocket6.writeDatagram(datagram, groupAddress6, 45454); ++messageNo; } diff --git a/examples/network/multicastsender/sender.h b/examples/network/multicastsender/sender.h index 8e10f88c0d..0af6f9aaec 100644 --- a/examples/network/multicastsender/sender.h +++ b/examples/network/multicastsender/sender.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -51,24 +51,16 @@ #ifndef SENDER_H #define SENDER_H -#include <QDialog> -#include <QHostAddress> - -QT_BEGIN_NAMESPACE -class QDialogButtonBox; -class QLabel; -class QPushButton; -class QTimer; -class QUdpSocket; -class QSpinBox; -QT_END_NAMESPACE +#include <QtWidgets> +#include <QtNetwork> +#include <QtCore> class Sender : public QDialog { Q_OBJECT public: - Sender(QWidget *parent = 0); + explicit Sender(QWidget *parent = nullptr); private slots: void ttlChanged(int newTtl); @@ -76,16 +68,14 @@ private slots: void sendDatagram(); private: - QLabel *statusLabel; - QLabel *ttlLabel; - QSpinBox *ttlSpinBox; - QPushButton *startButton; - QPushButton *quitButton; - QDialogButtonBox *buttonBox; - QUdpSocket *udpSocket; - QTimer *timer; - QHostAddress groupAddress; - int messageNo; + QLabel *statusLabel = nullptr; + QPushButton *startButton = nullptr; + QUdpSocket udpSocket4; + QUdpSocket udpSocket6; + QTimer timer; + QHostAddress groupAddress4; + QHostAddress groupAddress6; + int messageNo = 1; }; #endif diff --git a/examples/network/network-chat/network-chat.pro b/examples/network/network-chat/network-chat.pro index b20e8b2934..2e3cbbc489 100644 --- a/examples/network/network-chat/network-chat.pro +++ b/examples/network/network-chat/network-chat.pro @@ -11,6 +11,8 @@ SOURCES = chatdialog.cpp \ server.cpp FORMS = chatdialog.ui QT += network widgets +requires(qtConfig(udpsocket)) +requires(qtConfig(listwidget)) # install target.path = $$[QT_INSTALL_EXAMPLES]/network/network-chat diff --git a/examples/network/securesocketclient/certificateinfo.cpp b/examples/network/securesocketclient/certificateinfo.cpp index c8cd86bc72..81429fc655 100644 --- a/examples/network/securesocketclient/certificateinfo.cpp +++ b/examples/network/securesocketclient/certificateinfo.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -57,8 +57,8 @@ CertificateInfo::CertificateInfo(QWidget *parent) form = new Ui_CertificateInfo; form->setupUi(this); - connect(form->certificationPathView, SIGNAL(currentIndexChanged(int)), - this, SLOT(updateCertificateInfo(int))); + connect(form->certificationPathView, QOverload<int>::of(&QComboBox::currentIndexChanged), + this, &CertificateInfo::updateCertificateInfo); } CertificateInfo::~CertificateInfo() @@ -68,25 +68,23 @@ CertificateInfo::~CertificateInfo() void CertificateInfo::setCertificateChain(const QList<QSslCertificate> &chain) { - this->chain = chain; + certificateChain = chain; form->certificationPathView->clear(); - - for (int i = 0; i < chain.size(); ++i) { - const QSslCertificate &cert = chain.at(i); + for (int i = 0; i < certificateChain.size(); ++i) { + const QSslCertificate &cert = certificateChain.at(i); form->certificationPathView->addItem(tr("%1%2 (%3)").arg(!i ? QString() : tr("Issued by: ")) .arg(cert.subjectInfo(QSslCertificate::Organization).join(QLatin1Char(' '))) .arg(cert.subjectInfo(QSslCertificate::CommonName).join(QLatin1Char(' ')))); } - form->certificationPathView->setCurrentIndex(0); } void CertificateInfo::updateCertificateInfo(int index) { form->certificateInfoView->clear(); - if (index >= 0 && index < chain.size()) { - const QSslCertificate &cert = chain.at(index); + if (index >= 0 && index < certificateChain.size()) { + const QSslCertificate &cert = certificateChain.at(index); QStringList lines; lines << tr("Organization: %1").arg(cert.subjectInfo(QSslCertificate::Organization).join(QLatin1Char(' '))) << tr("Subunit: %1").arg(cert.subjectInfo(QSslCertificate::OrganizationalUnitName).join(QLatin1Char(' '))) @@ -101,9 +99,7 @@ void CertificateInfo::updateCertificateInfo(int index) << tr("Issuer Locality: %1").arg(cert.issuerInfo(QSslCertificate::LocalityName).join(QLatin1Char(' '))) << tr("Issuer State/Province: %1").arg(cert.issuerInfo(QSslCertificate::StateOrProvinceName).join(QLatin1Char(' '))) << tr("Issuer Common Name: %1").arg(cert.issuerInfo(QSslCertificate::CommonName).join(QLatin1Char(' '))); - foreach (QString line, lines) + for (const auto &line : lines) form->certificateInfoView->addItem(line); - } else { - form->certificateInfoView->clear(); } } diff --git a/examples/network/securesocketclient/certificateinfo.h b/examples/network/securesocketclient/certificateinfo.h index abc56dfbcd..9e079c5603 100644 --- a/examples/network/securesocketclient/certificateinfo.h +++ b/examples/network/securesocketclient/certificateinfo.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -51,8 +51,9 @@ #ifndef CERTIFICATEINFO_H #define CERTIFICATEINFO_H -#include <QtWidgets/QDialog> -#include <QtNetwork/QSslCertificate> +#include <QDialog> +#include <QList> +#include <QSslCertificate> QT_BEGIN_NAMESPACE class Ui_CertificateInfo; @@ -62,7 +63,7 @@ class CertificateInfo : public QDialog { Q_OBJECT public: - CertificateInfo(QWidget *parent = 0); + explicit CertificateInfo(QWidget *parent = nullptr); ~CertificateInfo(); void setCertificateChain(const QList<QSslCertificate> &chain); @@ -71,8 +72,8 @@ private slots: void updateCertificateInfo(int index); private: - Ui_CertificateInfo *form; - QList<QSslCertificate> chain; + Ui_CertificateInfo *form = nullptr; + QList<QSslCertificate> certificateChain; }; #endif diff --git a/examples/network/securesocketclient/certificateinfo.ui b/examples/network/securesocketclient/certificateinfo.ui index c5238eb3e1..3bea255e9e 100644 --- a/examples/network/securesocketclient/certificateinfo.ui +++ b/examples/network/securesocketclient/certificateinfo.ui @@ -42,7 +42,7 @@ <widget class="QListWidget" name="certificateInfoView"> <property name="font"> <font> - <pointsize>8</pointsize> + <pointsize>10</pointsize> </font> </property> <property name="wordWrap"> diff --git a/examples/network/securesocketclient/main.cpp b/examples/network/securesocketclient/main.cpp index e6dc60736f..e9c413577f 100644 --- a/examples/network/securesocketclient/main.cpp +++ b/examples/network/securesocketclient/main.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -50,6 +50,9 @@ #include <QApplication> #include <QMessageBox> +#include <QtNetwork> + +QT_REQUIRE_CONFIG(ssl); #include "sslclient.h" @@ -61,7 +64,7 @@ int main(int argc, char **argv) if (!QSslSocket::supportsSsl()) { QMessageBox::information(0, "Secure Socket Client", - "This system does not support OpenSSL."); + "This system does not support SSL/TLS."); return -1; } diff --git a/examples/network/securesocketclient/securesocketclient.pro b/examples/network/securesocketclient/securesocketclient.pro index f13ed57247..fb81ef6ed2 100644 --- a/examples/network/securesocketclient/securesocketclient.pro +++ b/examples/network/securesocketclient/securesocketclient.pro @@ -1,3 +1,5 @@ +requires(qtHaveModule(network)) + HEADERS += certificateinfo.h \ sslclient.h SOURCES += certificateinfo.cpp \ @@ -8,6 +10,8 @@ FORMS += certificateinfo.ui \ sslclient.ui \ sslerrors.ui QT += network widgets +requires(qtConfig(listwidget)) +requires(qtConfig(combobox)) # install target.path = $$[QT_INSTALL_EXAMPLES]/network/securesocketclient diff --git a/examples/network/securesocketclient/sslclient.cpp b/examples/network/securesocketclient/sslclient.cpp index 46d1919fd0..afeec033ff 100644 --- a/examples/network/securesocketclient/sslclient.cpp +++ b/examples/network/securesocketclient/sslclient.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -50,29 +50,17 @@ #include "certificateinfo.h" #include "sslclient.h" + #include "ui_sslclient.h" #include "ui_sslerrors.h" -#include <QtWidgets/QScrollBar> -#include <QtWidgets/QStyle> -#include <QtWidgets/QToolButton> -#include <QtWidgets/QMessageBox> -#include <QtNetwork/QSslCipher> +#include <QtCore> SslClient::SslClient(QWidget *parent) - : QWidget(parent), socket(0), padLock(0), executingDialog(false) + : QWidget(parent) { - form = new Ui_Form; - form->setupUi(this); - form->hostNameEdit->setSelection(0, form->hostNameEdit->text().size()); - form->sessionOutput->setHtml(tr("<not connected>")); - - connect(form->hostNameEdit, SIGNAL(textChanged(QString)), - this, SLOT(updateEnabledState())); - connect(form->connectButton, SIGNAL(clicked()), - this, SLOT(secureConnect())); - connect(form->sendButton, SIGNAL(clicked()), - this, SLOT(sendData())); + setupUi(); + setupSecureSocket(); } SslClient::~SslClient() @@ -82,17 +70,15 @@ SslClient::~SslClient() void SslClient::updateEnabledState() { - bool unconnected = !socket || socket->state() == QAbstractSocket::UnconnectedState; - + const bool unconnected = socket->state() == QAbstractSocket::UnconnectedState; form->hostNameEdit->setReadOnly(!unconnected); form->hostNameEdit->setFocusPolicy(unconnected ? Qt::StrongFocus : Qt::NoFocus); - form->hostNameLabel->setEnabled(unconnected); form->portBox->setEnabled(unconnected); form->portLabel->setEnabled(unconnected); form->connectButton->setEnabled(unconnected && !form->hostNameEdit->text().isEmpty()); - bool connected = socket && socket->state() == QAbstractSocket::ConnectedState; + const bool connected = socket->state() == QAbstractSocket::ConnectedState; form->sessionOutput->setEnabled(connected); form->sessionInput->setEnabled(connected); form->sessionInputLabel->setEnabled(connected); @@ -101,20 +87,6 @@ void SslClient::updateEnabledState() void SslClient::secureConnect() { - if (!socket) { - socket = new QSslSocket(this); - connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), - this, SLOT(socketStateChanged(QAbstractSocket::SocketState))); - connect(socket, SIGNAL(encrypted()), - this, SLOT(socketEncrypted())); - connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), - this, SLOT(socketError(QAbstractSocket::SocketError))); - connect(socket, SIGNAL(sslErrors(QList<QSslError>)), - this, SLOT(sslErrors(QList<QSslError>))); - connect(socket, SIGNAL(readyRead()), - this, SLOT(socketReadyRead())); - } - socket->connectToHostEncrypted(form->hostNameEdit->text(), form->portBox->value()); updateEnabledState(); } @@ -125,20 +97,18 @@ void SslClient::socketStateChanged(QAbstractSocket::SocketState state) return; updateEnabledState(); + if (state == QAbstractSocket::UnconnectedState) { + form->sessionInput->clear(); form->hostNameEdit->setPalette(QPalette()); form->hostNameEdit->setFocus(); form->cipherLabel->setText(tr("<none>")); - if (padLock) - padLock->hide(); + padLock->hide(); } } void SslClient::socketEncrypted() { - if (!socket) - return; // might have disconnected already - form->sessionOutput->clear(); form->sessionInput->setFocus(); @@ -146,36 +116,12 @@ void SslClient::socketEncrypted() palette.setColor(QPalette::Base, QColor(255, 255, 192)); form->hostNameEdit->setPalette(palette); - QSslCipher ciph = socket->sessionCipher(); - QString cipher = QString("%1, %2 (%3/%4)").arg(ciph.authenticationMethod()) - .arg(ciph.name()).arg(ciph.usedBits()).arg(ciph.supportedBits());; - form->cipherLabel->setText(cipher); - - if (!padLock) { - padLock = new QToolButton; - padLock->setIcon(QIcon(":/encrypted.png")); -#ifndef QT_NO_CURSOR - padLock->setCursor(Qt::ArrowCursor); -#endif - padLock->setToolTip(tr("Display encryption details.")); - - int extent = form->hostNameEdit->height() - 2; - padLock->resize(extent, extent); - padLock->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored); - - QHBoxLayout *layout = new QHBoxLayout(form->hostNameEdit); - layout->setMargin(form->hostNameEdit->style()->pixelMetric(QStyle::PM_DefaultFrameWidth)); - layout->setSpacing(0); - layout->addStretch(); - layout->addWidget(padLock); - - form->hostNameEdit->setLayout(layout); - - connect(padLock, SIGNAL(clicked()), - this, SLOT(displayCertificateInfo())); - } else { - padLock->show(); - } + const QSslCipher cipher = socket->sessionCipher(); + const QString cipherInfo = QString("%1, %2 (%3/%4)").arg(cipher.authenticationMethod()) + .arg(cipher.name()).arg(cipher.usedBits()) + .arg(cipher.supportedBits());; + form->cipherLabel->setText(cipherInfo); + padLock->show(); } void SslClient::socketReadyRead() @@ -185,7 +131,7 @@ void SslClient::socketReadyRead() void SslClient::sendData() { - QString input = form->sessionInput->text(); + const QString input = form->sessionInput->text(); appendString(input + '\n'); socket->write(input.toUtf8() + "\r\n"); form->sessionInput->clear(); @@ -193,7 +139,12 @@ void SslClient::sendData() void SslClient::socketError(QAbstractSocket::SocketError) { + if (handlingSocketError) + return; + + handlingSocketError = true; QMessageBox::critical(this, tr("Connection error"), socket->errorString()); + handlingSocketError = false; } void SslClient::sslErrors(const QList<QSslError> &errors) @@ -201,10 +152,10 @@ void SslClient::sslErrors(const QList<QSslError> &errors) QDialog errorDialog(this); Ui_SslErrors ui; ui.setupUi(&errorDialog); - connect(ui.certificateChainButton, SIGNAL(clicked()), - this, SLOT(displayCertificateInfo())); + connect(ui.certificateChainButton, &QPushButton::clicked, + this, &SslClient::displayCertificateInfo); - foreach (const QSslError &error, errors) + for (const auto &error : errors) ui.sslErrorList->addItem(error.errorString()); executingDialog = true; @@ -219,10 +170,69 @@ void SslClient::sslErrors(const QList<QSslError> &errors) void SslClient::displayCertificateInfo() { - CertificateInfo *info = new CertificateInfo(this); - info->setCertificateChain(socket->peerCertificateChain()); - info->exec(); - info->deleteLater(); + CertificateInfo info; + info.setCertificateChain(socket->peerCertificateChain()); + info.exec(); +} + +void SslClient::setupUi() +{ + if (form) + return; + + form = new Ui_Form; + form->setupUi(this); + form->hostNameEdit->setSelection(0, form->hostNameEdit->text().size()); + form->sessionOutput->setHtml(tr("<not connected>")); + + connect(form->hostNameEdit, SIGNAL(textChanged(QString)), + this, SLOT(updateEnabledState())); + connect(form->connectButton, SIGNAL(clicked()), + this, SLOT(secureConnect())); + connect(form->sendButton, SIGNAL(clicked()), + this, SLOT(sendData())); + + padLock = new QToolButton; + padLock->setIcon(QIcon(":/encrypted.png")); + connect(padLock, SIGNAL(clicked()), this, SLOT(displayCertificateInfo())); + +#if QT_CONFIG(cursor) + padLock->setCursor(Qt::ArrowCursor); +#endif + padLock->setToolTip(tr("Display encryption details.")); + + const int extent = form->hostNameEdit->height() - 2; + padLock->resize(extent, extent); + padLock->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored); + + QHBoxLayout *layout = new QHBoxLayout(form->hostNameEdit); + layout->setMargin(form->hostNameEdit->style()->pixelMetric(QStyle::PM_DefaultFrameWidth)); + layout->setSpacing(0); + layout->addStretch(); + layout->addWidget(padLock); + + form->hostNameEdit->setLayout(layout); + padLock->hide(); +} + +void SslClient::setupSecureSocket() +{ + if (socket) + return; + + socket = new QSslSocket(this); + + connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), + this, SLOT(socketStateChanged(QAbstractSocket::SocketState))); + connect(socket, SIGNAL(encrypted()), + this, SLOT(socketEncrypted())); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), + this, SLOT(socketError(QAbstractSocket::SocketError))); + connect(socket, SIGNAL(sslErrors(QList<QSslError>)), + this, SLOT(sslErrors(QList<QSslError>))); + connect(socket, SIGNAL(readyRead()), + this, SLOT(socketReadyRead())); + } void SslClient::appendString(const QString &line) diff --git a/examples/network/securesocketclient/sslclient.h b/examples/network/securesocketclient/sslclient.h index d3baefbc56..63fdbef77d 100644 --- a/examples/network/securesocketclient/sslclient.h +++ b/examples/network/securesocketclient/sslclient.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2017 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. @@ -51,13 +51,13 @@ #ifndef SSLCLIENT_H #define SSLCLIENT_H -#include <QtWidgets/QWidget> -#include <QtNetwork/QAbstractSocket> -#include <QtNetwork/QSslSocket> +#include <QtNetwork> + +QT_REQUIRE_CONFIG(ssl); + +#include <QtWidgets> QT_BEGIN_NAMESPACE -class QSslSocket; -class QToolButton; class Ui_Form; QT_END_NAMESPACE @@ -65,7 +65,7 @@ class SslClient : public QWidget { Q_OBJECT public: - SslClient(QWidget *parent = 0); + explicit SslClient(QWidget *parent = nullptr); ~SslClient(); private slots: @@ -80,12 +80,15 @@ private slots: void displayCertificateInfo(); private: + void setupUi(); + void setupSecureSocket(); void appendString(const QString &line); - QSslSocket *socket; - QToolButton *padLock; - Ui_Form *form; - bool executingDialog; + QSslSocket *socket = nullptr; + QToolButton *padLock = nullptr; + Ui_Form *form = nullptr; + bool handlingSocketError = false; + bool executingDialog = false; }; #endif diff --git a/examples/network/securesocketclient/sslclient.ui b/examples/network/securesocketclient/sslclient.ui index 19bae83a09..7821b04e76 100644 --- a/examples/network/securesocketclient/sslclient.ui +++ b/examples/network/securesocketclient/sslclient.ui @@ -10,6 +10,12 @@ <height>320</height> </rect> </property> + <property name="minimumSize"> + <size> + <width>343</width> + <height>320</height> + </size> + </property> <property name="windowTitle"> <string>Secure Socket Client</string> </property> @@ -114,8 +120,8 @@ <string><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-size:9pt;"></p></body></html></string> +</style></head><body style=" font-family:'.SF NS Text'; font-size:13pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-size:9pt;"><br /></p></body></html></string> </property> </widget> </item> diff --git a/examples/network/threadedfortuneserver/fortuneserver.cpp b/examples/network/threadedfortuneserver/fortuneserver.cpp index 01b77e2aba..791ffc71f4 100644 --- a/examples/network/threadedfortuneserver/fortuneserver.cpp +++ b/examples/network/threadedfortuneserver/fortuneserver.cpp @@ -51,6 +51,8 @@ #include "fortuneserver.h" #include "fortunethread.h" +#include <QRandomGenerator> + #include <stdlib.h> //! [0] @@ -70,7 +72,7 @@ FortuneServer::FortuneServer(QObject *parent) //! [1] void FortuneServer::incomingConnection(qintptr socketDescriptor) { - QString fortune = fortunes.at(qrand() % fortunes.size()); + QString fortune = fortunes.at(QRandomGenerator::global()->bounded(fortunes.size())); FortuneThread *thread = new FortuneThread(socketDescriptor, fortune, this); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); diff --git a/examples/network/threadedfortuneserver/main.cpp b/examples/network/threadedfortuneserver/main.cpp index 3a54585fbc..fdacb28945 100644 --- a/examples/network/threadedfortuneserver/main.cpp +++ b/examples/network/threadedfortuneserver/main.cpp @@ -60,6 +60,5 @@ int main(int argc, char *argv[]) QApplication app(argc, argv); Dialog dialog; dialog.show(); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); return app.exec(); } diff --git a/examples/network/torrent/main.cpp b/examples/network/torrent/main.cpp index de7516ed3f..6430d2e5f3 100644 --- a/examples/network/torrent/main.cpp +++ b/examples/network/torrent/main.cpp @@ -55,7 +55,6 @@ int main(int argc, char *argv[]) { QApplication app(argc, argv); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); Q_INIT_RESOURCE(icons); diff --git a/examples/network/torrent/torrent.pro b/examples/network/torrent/torrent.pro index 16a44d8aad..c640c3b5d0 100644 --- a/examples/network/torrent/torrent.pro +++ b/examples/network/torrent/torrent.pro @@ -1,4 +1,5 @@ QT += network widgets +requires(qtConfig(filedialog)) HEADERS += addtorrentdialog.h \ bencodeparser.h \ diff --git a/examples/network/torrent/torrentclient.cpp b/examples/network/torrent/torrentclient.cpp index ba87924ff9..95232646ab 100644 --- a/examples/network/torrent/torrentclient.cpp +++ b/examples/network/torrent/torrentclient.cpp @@ -692,7 +692,7 @@ void TorrentClient::connectToPeers() // Start as many connections as we can while (!weighedPeers.isEmpty() && ConnectionManager::instance()->canAddConnection() - && (qrand() % (ConnectionManager::instance()->maxConnections() / 2))) { + && (QRandomGenerator::global()->bounded(ConnectionManager::instance()->maxConnections() / 2))) { PeerWireClient *client = new PeerWireClient(ConnectionManager::instance()->clientId(), this); RateController::instance()->addSocket(client); ConnectionManager::instance()->addConnection(client); @@ -701,7 +701,7 @@ void TorrentClient::connectToPeers() d->connections << client; // Pick a random peer from the list of weighed peers. - TorrentPeer *peer = weighedPeers.takeAt(qrand() % weighedPeers.size()); + TorrentPeer *peer = weighedPeers.takeAt(QRandomGenerator::global()->bounded(weighedPeers.size())); weighedPeers.removeAll(peer); peer->connectStart = QDateTime::currentSecsSinceEpoch(); peer->lastVisited = peer->connectStart; @@ -1114,7 +1114,7 @@ void TorrentClient::scheduleUploads() } if ((client->peerWireState() & PeerWireClient::ChokingPeer) == 0) { - if ((qrand() % 10) == 0) + if ((QRandomGenerator::global()->bounded(10)) == 0) client->abort(); else client->chokePeer(); @@ -1128,7 +1128,7 @@ void TorrentClient::scheduleUploads() // random peer to allow it to compete for a position among the // downloaders. (This is known as an "optimistic unchoke".) if (!allClients.isEmpty()) { - PeerWireClient *client = allClients[qrand() % allClients.size()]; + PeerWireClient *client = allClients[QRandomGenerator::global()->bounded(allClients.size())]; if (client->peerWireState() & PeerWireClient::ChokingPeer) client->unchokePeer(); } @@ -1189,7 +1189,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client) piece = d->payloads.value(client); if (!piece) { QList<TorrentPiece *> values = d->pendingPieces.values(); - piece = values.value(qrand() % values.size()); + piece = values.value(QRandomGenerator::global()->bounded(values.size())); piece->inProgress = true; d->payloads.insert(client, piece); } @@ -1246,14 +1246,14 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client) ++it; } if (!partialPieces.isEmpty()) - piece = partialPieces.value(qrand() % partialPieces.size()); + piece = partialPieces.value(QRandomGenerator::global()->bounded(partialPieces.size())); if (!piece) { // Pick a random piece 3 out of 4 times; otherwise, pick either // one of the most common or the least common pieces available, // depending on the state we're in. int pieceIndex = 0; - if (d->state == WarmingUp || (qrand() & 4) == 0) { + if (d->state == WarmingUp || (QRandomGenerator::global()->generate() & 4) == 0) { int *occurrences = new int[d->pieceCount]; memset(occurrences, 0, d->pieceCount * sizeof(int)); @@ -1293,7 +1293,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client) } // Select one piece randomly - pieceIndex = piecesReadyForDownload.at(qrand() % piecesReadyForDownload.size()); + pieceIndex = piecesReadyForDownload.at(QRandomGenerator::global()->bounded(piecesReadyForDownload.size())); delete [] occurrences; } else { // Make up a list of available piece indices, and pick @@ -1304,7 +1304,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client) if (incompletePiecesAvailableToClient.testBit(i)) values << i; } - pieceIndex = values.at(qrand() % values.size()); + pieceIndex = values.at(QRandomGenerator::global()->bounded(values.size())); } // Create a new TorrentPiece and fill in all initial @@ -1396,8 +1396,8 @@ int TorrentClient::requestBlocks(PeerWireClient *client, TorrentPiece *piece, in // speedup comes from an increased chance of receiving // different blocks from the different peers. for (int i = 0; i < bits.size(); ++i) { - int a = qrand() % bits.size(); - int b = qrand() % bits.size(); + int a = QRandomGenerator::global()->bounded(bits.size()); + int b = QRandomGenerator::global()->bounded(bits.size()); int tmp = bits[a]; bits[a] = bits[b]; bits[b] = tmp; |