summaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
authorLiang Qi <liang.qi@qt.io>2017-09-26 16:08:55 +0200
committerLiang Qi <liang.qi@qt.io>2017-09-26 16:14:54 +0200
commitaadfe7d634de04519102c5827ca885dc2e2199c9 (patch)
treed92db346ca95332b177036a53f1f6beb2e24fb74 /examples
parent4b6c1448047362b8c38d265e6414f0e3e59b8d37 (diff)
parenta732e16d5fd9dbf8a0289fec9f948b12e9ba2c19 (diff)
Merge remote-tracking branch 'origin/5.10' into dev
Conflicts: src/gui/kernel/qguiapplication.cpp src/platformsupport/input/libinput/qlibinputpointer.cpp src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.h src/plugins/platforms/cocoa/qcocoawindow.h src/testlib/qtestsystem.h Change-Id: I5975ffb3261c2dd82fe02ec4e57df7c0950226c5
Diffstat (limited to 'examples')
-rw-r--r--examples/corelib/ipc/localfortuneclient/client.cpp67
-rw-r--r--examples/corelib/ipc/localfortuneclient/client.h13
-rw-r--r--examples/corelib/ipc/localfortuneclient/main.cpp1
-rw-r--r--examples/corelib/ipc/localfortuneserver/main.cpp2
-rw-r--r--examples/corelib/ipc/localfortuneserver/server.cpp36
-rw-r--r--examples/corelib/ipc/localfortuneserver/server.h4
-rw-r--r--examples/network/broadcastsender/sender.cpp22
-rw-r--r--examples/network/broadcastsender/sender.h19
-rw-r--r--examples/network/doc/images/http-example.pngbin7006 -> 8099 bytes
-rw-r--r--examples/network/http/httpwindow.cpp32
-rw-r--r--examples/network/http/httpwindow.h4
-rw-r--r--examples/network/multicastsender/sender.cpp41
-rw-r--r--examples/network/multicastsender/sender.h32
-rw-r--r--examples/network/securesocketclient/certificateinfo.cpp22
-rw-r--r--examples/network/securesocketclient/certificateinfo.h13
-rw-r--r--examples/network/securesocketclient/certificateinfo.ui2
-rw-r--r--examples/network/securesocketclient/main.cpp7
-rw-r--r--examples/network/securesocketclient/securesocketclient.pro2
-rw-r--r--examples/network/securesocketclient/sslclient.cpp168
-rw-r--r--examples/network/securesocketclient/sslclient.h25
-rw-r--r--examples/network/securesocketclient/sslclient.ui10
-rw-r--r--examples/opengl/hellogl2/glwidget.cpp7
-rw-r--r--examples/opengl/hellogl2/glwidget.h5
-rw-r--r--examples/opengl/hellogl2/main.cpp27
-rw-r--r--examples/opengl/hellowindow/main.cpp27
-rw-r--r--examples/opengl/qopenglwidget/main.cpp19
-rw-r--r--examples/opengl/threadedqopenglwidget/main.cpp15
-rw-r--r--examples/sql/cachedtable/tableeditor.cpp6
-rw-r--r--examples/sql/cachedtable/tableeditor.h2
-rw-r--r--examples/sql/connection.h12
-rw-r--r--examples/sql/doc/src/drilldown.qdoc33
-rw-r--r--examples/sql/drilldown/imageitem.cpp6
-rw-r--r--examples/sql/drilldown/imageitem.h4
-rw-r--r--examples/sql/drilldown/informationwindow.cpp18
-rw-r--r--examples/sql/drilldown/informationwindow.h20
-rw-r--r--examples/sql/drilldown/main.cpp11
-rw-r--r--examples/sql/drilldown/view.cpp36
-rw-r--r--examples/sql/drilldown/view.h4
-rw-r--r--examples/sql/masterdetail/database.h12
-rw-r--r--examples/sql/masterdetail/dialog.cpp12
-rw-r--r--examples/sql/masterdetail/dialog.h8
-rw-r--r--examples/sql/masterdetail/main.cpp13
-rw-r--r--examples/sql/masterdetail/mainwindow.cpp43
-rw-r--r--examples/sql/masterdetail/mainwindow.h2
-rw-r--r--examples/sql/querymodel/customsqlmodel.h2
-rw-r--r--examples/sql/querymodel/editablesqlmodel.h2
-rw-r--r--examples/sql/querymodel/main.cpp9
-rw-r--r--examples/sql/relationaltablemodel/relationaltablemodel.cpp3
-rw-r--r--examples/sql/sqlbrowser/browser.cpp6
-rw-r--r--examples/sql/sqlbrowser/browser.h6
-rw-r--r--examples/sql/sqlbrowser/connectionwidget.cpp5
-rw-r--r--examples/sql/sqlbrowser/connectionwidget.h2
-rw-r--r--examples/sql/sqlbrowser/main.cpp14
-rw-r--r--examples/sql/sqlbrowser/qsqlconnectiondialog.h2
-rw-r--r--examples/sql/sqlwidgetmapper/window.cpp12
-rw-r--r--examples/sql/sqlwidgetmapper/window.h2
-rw-r--r--examples/sql/tablemodel/tablemodel.cpp10
-rw-r--r--examples/widgets/dialogs/dialogs.pro1
-rw-r--r--examples/widgets/itemviews/storageview/main.cpp10
-rw-r--r--examples/widgets/itemviews/storageview/storagemodel.cpp53
-rw-r--r--examples/widgets/itemviews/storageview/storagemodel.h14
61 files changed, 587 insertions, 430 deletions
diff --git a/examples/corelib/ipc/localfortuneclient/client.cpp b/examples/corelib/ipc/localfortuneclient/client.cpp
index d5a1525769..8d415f73aa 100644
--- a/examples/corelib/ipc/localfortuneclient/client.cpp
+++ b/examples/corelib/ipc/localfortuneclient/client.cpp
@@ -54,45 +54,45 @@
#include "client.h"
Client::Client(QWidget *parent)
- : QDialog(parent)
+ : QDialog(parent),
+ hostLineEdit(new QLineEdit("fortune")),
+ getFortuneButton(new QPushButton(tr("Get Fortune"))),
+ statusLabel(new QLabel(tr("This examples requires that you run the "
+ "Local Fortune Server example as well."))),
+ socket(new QLocalSocket(this))
{
- hostLabel = new QLabel(tr("&Server name:"));
- hostLineEdit = new QLineEdit("fortune");
-
+ setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
+ QLabel *hostLabel = new QLabel(tr("&Server name:"));
hostLabel->setBuddy(hostLineEdit);
- statusLabel = new QLabel(tr("This examples requires that you run the "
- "Fortune Server example as well."));
statusLabel->setWordWrap(true);
- getFortuneButton = new QPushButton(tr("Get Fortune"));
getFortuneButton->setDefault(true);
+ QPushButton *quitButton = new QPushButton(tr("Quit"));
- quitButton = new QPushButton(tr("Quit"));
-
- buttonBox = new QDialogButtonBox;
+ QDialogButtonBox *buttonBox = new QDialogButtonBox;
buttonBox->addButton(getFortuneButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);
- socket = new QLocalSocket(this);
+ in.setDevice(socket);
+ in.setVersion(QDataStream::Qt_5_10);
- connect(hostLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(enableGetFortuneButton()));
- connect(getFortuneButton, SIGNAL(clicked()),
- this, SLOT(requestNewFortune()));
- connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
- connect(socket, SIGNAL(readyRead()), this, SLOT(readFortune()));
- connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)),
- this, SLOT(displayError(QLocalSocket::LocalSocketError)));
+ connect(hostLineEdit, &QLineEdit::textChanged,
+ this, &Client::enableGetFortuneButton);
+ connect(getFortuneButton, &QPushButton::clicked,
+ this, &Client::requestNewFortune);
+ connect(quitButton, &QPushButton::clicked, this, &Client::close);
+ connect(socket, &QLocalSocket::readyRead, this, &Client::readFortune);
+ connect(socket, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error),
+ this, &Client::displayError);
- QGridLayout *mainLayout = new QGridLayout;
+ QGridLayout *mainLayout = new QGridLayout(this);
mainLayout->addWidget(hostLabel, 0, 0);
mainLayout->addWidget(hostLineEdit, 0, 1);
mainLayout->addWidget(statusLabel, 2, 0, 1, 2);
mainLayout->addWidget(buttonBox, 3, 0, 1, 2);
- setLayout(mainLayout);
- setWindowTitle(tr("Fortune Client"));
+ setWindowTitle(QGuiApplication::applicationDisplayName());
hostLineEdit->setFocus();
}
@@ -106,11 +106,9 @@ void Client::requestNewFortune()
void Client::readFortune()
{
- QDataStream in(socket);
- in.setVersion(QDataStream::Qt_4_0);
-
if (blockSize == 0) {
- // Relies on the fact that QDataStream format streams a quint32 into sizeof(quint32) bytes
+ // Relies on the fact that QDataStream serializes a quint32 into
+ // sizeof(quint32) bytes
if (socket->bytesAvailable() < (int)sizeof(quint32))
return;
in >> blockSize;
@@ -123,7 +121,7 @@ void Client::readFortune()
in >> nextFortune;
if (nextFortune == currentFortune) {
- QTimer::singleShot(0, this, SLOT(requestNewFortune()));
+ QTimer::singleShot(0, this, &Client::requestNewFortune);
return;
}
@@ -136,21 +134,22 @@ void Client::displayError(QLocalSocket::LocalSocketError socketError)
{
switch (socketError) {
case QLocalSocket::ServerNotFoundError:
- QMessageBox::information(this, tr("Fortune Client"),
- tr("The host was not found. Please check the "
- "host name and port settings."));
+ QMessageBox::information(this, tr("Local Fortune Client"),
+ tr("The host was not found. Please make sure "
+ "that the server is running and that the "
+ "server name is correct."));
break;
case QLocalSocket::ConnectionRefusedError:
- QMessageBox::information(this, tr("Fortune Client"),
+ QMessageBox::information(this, tr("Local Fortune Client"),
tr("The connection was refused by the peer. "
"Make sure the fortune server is running, "
- "and check that the host name and port "
- "settings are correct."));
+ "and check that the server name "
+ "is correct."));
break;
case QLocalSocket::PeerClosedError:
break;
default:
- QMessageBox::information(this, tr("Fortune Client"),
+ QMessageBox::information(this, tr("Local Fortune Client"),
tr("The following error occurred: %1.")
.arg(socket->errorString()));
}
diff --git a/examples/corelib/ipc/localfortuneclient/client.h b/examples/corelib/ipc/localfortuneclient/client.h
index 8e628efcee..0c1ede94c9 100644
--- a/examples/corelib/ipc/localfortuneclient/client.h
+++ b/examples/corelib/ipc/localfortuneclient/client.h
@@ -52,11 +52,11 @@
#define CLIENT_H
#include <QDialog>
+#include <QDataStream>
#include <qlocalsocket.h>
QT_BEGIN_NAMESPACE
-class QDialogButtonBox;
class QLabel;
class QLineEdit;
class QPushButton;
@@ -68,7 +68,7 @@ class Client : public QDialog
Q_OBJECT
public:
- Client(QWidget *parent = 0);
+ explicit Client(QWidget *parent = nullptr);
private slots:
void requestNewFortune();
@@ -77,16 +77,15 @@ private slots:
void enableGetFortuneButton();
private:
- QLabel *hostLabel;
QLineEdit *hostLineEdit;
- QLabel *statusLabel;
QPushButton *getFortuneButton;
- QPushButton *quitButton;
- QDialogButtonBox *buttonBox;
+ QLabel *statusLabel;
QLocalSocket *socket;
- QString currentFortune;
+ QDataStream in;
quint32 blockSize;
+
+ QString currentFortune;
};
#endif
diff --git a/examples/corelib/ipc/localfortuneclient/main.cpp b/examples/corelib/ipc/localfortuneclient/main.cpp
index dd13a05be9..ed5cf4c569 100644
--- a/examples/corelib/ipc/localfortuneclient/main.cpp
+++ b/examples/corelib/ipc/localfortuneclient/main.cpp
@@ -55,6 +55,7 @@
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
+ QGuiApplication::setApplicationDisplayName(Client::tr("Local Fortune Client"));
Client client;
client.show();
return app.exec();
diff --git a/examples/corelib/ipc/localfortuneserver/main.cpp b/examples/corelib/ipc/localfortuneserver/main.cpp
index cd066a0acd..6f8ec539fe 100644
--- a/examples/corelib/ipc/localfortuneserver/main.cpp
+++ b/examples/corelib/ipc/localfortuneserver/main.cpp
@@ -58,8 +58,8 @@
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
+ QGuiApplication::setApplicationDisplayName(Server::tr("Local Fortune Server"));
Server server;
server.show();
- qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
return app.exec();
}
diff --git a/examples/corelib/ipc/localfortuneserver/server.cpp b/examples/corelib/ipc/localfortuneserver/server.cpp
index 2eee4760be..9b8b08bd17 100644
--- a/examples/corelib/ipc/localfortuneserver/server.cpp
+++ b/examples/corelib/ipc/localfortuneserver/server.cpp
@@ -60,22 +60,21 @@
Server::Server(QWidget *parent)
: QDialog(parent)
{
- statusLabel = new QLabel;
- statusLabel->setWordWrap(true);
- quitButton = new QPushButton(tr("Quit"));
- quitButton->setAutoDefault(false);
+ setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
server = new QLocalServer(this);
if (!server->listen("fortune")) {
- QMessageBox::critical(this, tr("Fortune Server"),
+ QMessageBox::critical(this, tr("Local Fortune Server"),
tr("Unable to start the server: %1.")
.arg(server->errorString()));
close();
return;
}
+ QLabel *statusLabel = new QLabel;
+ statusLabel->setWordWrap(true);
statusLabel->setText(tr("The server is running.\n"
- "Run the Fortune Client example now."));
+ "Run the Local Fortune Client example now."));
fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
<< tr("You've got to think about tomorrow.")
@@ -85,35 +84,36 @@ Server::Server(QWidget *parent)
<< tr("You cannot kill time without injuring eternity.")
<< tr("Computers are not intelligent. They only think they are.");
- connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
- connect(server, SIGNAL(newConnection()), this, SLOT(sendFortune()));
+ QPushButton *quitButton = new QPushButton(tr("Quit"));
+ quitButton->setAutoDefault(false);
+ connect(quitButton, &QPushButton::clicked, this, &Server::close);
+ connect(server, &QLocalServer::newConnection, this, &Server::sendFortune);
QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addStretch(1);
buttonLayout->addWidget(quitButton);
buttonLayout->addStretch(1);
- QVBoxLayout *mainLayout = new QVBoxLayout;
+ QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(statusLabel);
mainLayout->addLayout(buttonLayout);
- setLayout(mainLayout);
- setWindowTitle(tr("Fortune Server"));
+ setWindowTitle(QGuiApplication::applicationDisplayName());
}
void Server::sendFortune()
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
- out.setVersion(QDataStream::Qt_4_0);
- out << (quint32)0;
- out << fortunes.at(qrand() % fortunes.size());
- out.device()->seek(0);
- out << (quint32)(block.size() - sizeof(quint32));
+ out.setVersion(QDataStream::Qt_5_10);
+ const int fortuneIndex = QRandomGenerator::bounded(0, fortunes.size());
+ const QString &message = fortunes.at(fortuneIndex);
+ out << quint32(message.size());
+ out << message;
QLocalSocket *clientConnection = server->nextPendingConnection();
- connect(clientConnection, SIGNAL(disconnected()),
- clientConnection, SLOT(deleteLater()));
+ connect(clientConnection, &QLocalSocket::disconnected,
+ clientConnection, &QLocalSocket::deleteLater);
clientConnection->write(block);
clientConnection->flush();
diff --git a/examples/corelib/ipc/localfortuneserver/server.h b/examples/corelib/ipc/localfortuneserver/server.h
index c77b4e8127..6b90ba5932 100644
--- a/examples/corelib/ipc/localfortuneserver/server.h
+++ b/examples/corelib/ipc/localfortuneserver/server.h
@@ -64,14 +64,12 @@ class Server : public QDialog
Q_OBJECT
public:
- Server(QWidget *parent = 0);
+ explicit Server(QWidget *parent = nullptr);
private slots:
void sendFortune();
private:
- QLabel *statusLabel;
- QPushButton *quitButton;
QLocalServer *server;
QStringList fortunes;
};
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
index 16b0539b1b..c5f3ef1649 100644
--- a/examples/network/doc/images/http-example.png
+++ b/examples/network/doc/images/http-example.png
Binary files differ
diff --git a/examples/network/http/httpwindow.cpp b/examples/network/http/httpwindow.cpp
index 9640907673..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)
@@ -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);
}
@@ -252,7 +260,9 @@ void HttpWindow::httpFinished()
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 f942c33952..20ad2bb4da 100644
--- a/examples/network/http/httpwindow.h
+++ b/examples/network/http/httpwindow.h
@@ -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/multicastsender/sender.cpp b/examples/network/multicastsender/sender.cpp
index 4aa65fee27..cb4bf45672 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,35 @@
**
****************************************************************************/
-#include <QtWidgets>
-#include <QtNetwork>
-
#include "sender.h"
Sender::Sender(QWidget *parent)
- : QDialog(parent)
+ : QDialog(parent),
+ groupAddress(QStringLiteral("239.255.43.21"))
{
- groupAddress = QHostAddress("239.255.43.21");
-
statusLabel = new QLabel(tr("Ready to multicast datagrams to group %1 on port 45454").arg(groupAddress.toString()));
- ttlLabel = new QLabel(tr("TTL for multicast datagrams:"));
- ttlSpinBox = new QSpinBox;
+ auto ttlLabel = new QLabel(tr("TTL for 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 +88,19 @@ Sender::Sender(QWidget *parent)
void Sender::ttlChanged(int newTtl)
{
- udpSocket->setSocketOption(QAbstractSocket::MulticastTtlOption, newTtl);
+ udpSocket.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);
+ udpSocket.writeDatagram(datagram, groupAddress, 45454);
++messageNo;
}
diff --git a/examples/network/multicastsender/sender.h b/examples/network/multicastsender/sender.h
index 8e10f88c0d..5d8769790e 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,12 @@ private slots:
void sendDatagram();
private:
- QLabel *statusLabel;
- QLabel *ttlLabel;
- QSpinBox *ttlSpinBox;
- QPushButton *startButton;
- QPushButton *quitButton;
- QDialogButtonBox *buttonBox;
- QUdpSocket *udpSocket;
- QTimer *timer;
+ QLabel *statusLabel = nullptr;
+ QPushButton *startButton = nullptr;
+ QUdpSocket udpSocket;
+ QTimer timer;
QHostAddress groupAddress;
- int messageNo;
+ int messageNo = 1;
};
#endif
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..98d2041754 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 \
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("&lt;not connected&gt;"));
-
- 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("&lt;not connected&gt;"));
+
+ 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>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot;-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;&quot;&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'.SF NS Text'; font-size:13pt; font-weight:400; font-style:normal;&quot;&gt;
+&lt;p style=&quot;-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;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
diff --git a/examples/opengl/hellogl2/glwidget.cpp b/examples/opengl/hellogl2/glwidget.cpp
index fc961da4c4..318adb5043 100644
--- a/examples/opengl/hellogl2/glwidget.cpp
+++ b/examples/opengl/hellogl2/glwidget.cpp
@@ -54,6 +54,8 @@
#include <QCoreApplication>
#include <math.h>
+bool GLWidget::m_transparent = false;
+
GLWidget::GLWidget(QWidget *parent)
: QOpenGLWidget(parent),
m_xRot(0),
@@ -61,10 +63,9 @@ GLWidget::GLWidget(QWidget *parent)
m_zRot(0),
m_program(0)
{
- m_core = QCoreApplication::arguments().contains(QStringLiteral("--coreprofile"));
+ m_core = QSurfaceFormat::defaultFormat().profile() == QSurfaceFormat::CoreProfile;
// --transparent causes the clear color to be transparent. Therefore, on systems that
// support it, the widget will become transparent apart from the logo.
- m_transparent = QCoreApplication::arguments().contains(QStringLiteral("--transparent"));
if (m_transparent) {
QSurfaceFormat fmt = format();
fmt.setAlphaBufferSize(8);
@@ -127,6 +128,8 @@ void GLWidget::setZRotation(int angle)
void GLWidget::cleanup()
{
+ if (m_program == nullptr)
+ return;
makeCurrent();
m_logoVbo.destroy();
delete m_program;
diff --git a/examples/opengl/hellogl2/glwidget.h b/examples/opengl/hellogl2/glwidget.h
index cff5633893..21dd200dc7 100644
--- a/examples/opengl/hellogl2/glwidget.h
+++ b/examples/opengl/hellogl2/glwidget.h
@@ -68,6 +68,9 @@ public:
GLWidget(QWidget *parent = 0);
~GLWidget();
+ static bool isTransparent() { return m_transparent; }
+ static void setTransparent(bool t) { m_transparent = t; }
+
QSize minimumSizeHint() const override;
QSize sizeHint() const override;
@@ -108,7 +111,7 @@ private:
QMatrix4x4 m_proj;
QMatrix4x4 m_camera;
QMatrix4x4 m_world;
- bool m_transparent;
+ static bool m_transparent;
};
#endif
diff --git a/examples/opengl/hellogl2/main.cpp b/examples/opengl/hellogl2/main.cpp
index 143f659eb6..b52a5a37d3 100644
--- a/examples/opengl/hellogl2/main.cpp
+++ b/examples/opengl/hellogl2/main.cpp
@@ -51,25 +51,46 @@
#include <QApplication>
#include <QDesktopWidget>
#include <QSurfaceFormat>
+#include <QCommandLineParser>
+#include <QCommandLineOption>
+#include "glwidget.h"
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
+ QCoreApplication::setApplicationName("Qt Hello GL 2 Example");
+ QCoreApplication::setOrganizationName("QtProject");
+ QCoreApplication::setApplicationVersion(QT_VERSION_STR);
+ QCommandLineParser parser;
+ parser.setApplicationDescription(QCoreApplication::applicationName());
+ parser.addHelpOption();
+ parser.addVersionOption();
+ QCommandLineOption multipleSampleOption("multisample", "Multisampling");
+ parser.addOption(multipleSampleOption);
+ QCommandLineOption coreProfileOption("coreprofile", "Use core profile");
+ parser.addOption(coreProfileOption);
+ QCommandLineOption transparentOption("transparent", "Transparent window");
+ parser.addOption(transparentOption);
+
+ parser.process(app);
+
QSurfaceFormat fmt;
fmt.setDepthBufferSize(24);
- if (QCoreApplication::arguments().contains(QStringLiteral("--multisample")))
+ if (parser.isSet(multipleSampleOption))
fmt.setSamples(4);
- if (QCoreApplication::arguments().contains(QStringLiteral("--coreprofile"))) {
+ if (parser.isSet(coreProfileOption)) {
fmt.setVersion(3, 2);
fmt.setProfile(QSurfaceFormat::CoreProfile);
}
QSurfaceFormat::setDefaultFormat(fmt);
MainWindow mainWindow;
- if (QCoreApplication::arguments().contains(QStringLiteral("--transparent"))) {
+
+ GLWidget::setTransparent(parser.isSet(transparentOption));
+ if (GLWidget::isTransparent()) {
mainWindow.setAttribute(Qt::WA_TranslucentBackground);
mainWindow.setAttribute(Qt::WA_NoSystemBackground, false);
}
diff --git a/examples/opengl/hellowindow/main.cpp b/examples/opengl/hellowindow/main.cpp
index a20e7002a1..7f0be39f5d 100644
--- a/examples/opengl/hellowindow/main.cpp
+++ b/examples/opengl/hellowindow/main.cpp
@@ -52,6 +52,8 @@
#include <qpa/qplatformintegration.h>
+#include <QCommandLineParser>
+#include <QCommandLineOption>
#include <QGuiApplication>
#include <QScreen>
#include <QThread>
@@ -60,9 +62,26 @@ int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
+ QCoreApplication::setApplicationName("Qt HelloWindow GL Example");
+ QCoreApplication::setOrganizationName("QtProject");
+ QCoreApplication::setApplicationVersion(QT_VERSION_STR);
+ QCommandLineParser parser;
+ parser.setApplicationDescription(QCoreApplication::applicationName());
+ parser.addHelpOption();
+ parser.addVersionOption();
+ QCommandLineOption multipleOption("multiple", "Create multiple windows");
+ parser.addOption(multipleOption);
+ QCommandLineOption multipleSampleOption("multisample", "Multisampling");
+ parser.addOption(multipleSampleOption);
+ QCommandLineOption multipleScreenOption("multiscreen", "Run on multiple screens");
+ parser.addOption(multipleScreenOption);
+ QCommandLineOption timeoutOption("timeout", "Close after 10s");
+ parser.addOption(timeoutOption);
+ parser.process(app);
+
// Some platforms can only have one window per screen. Therefore we need to differentiate.
- const bool multipleWindows = QGuiApplication::arguments().contains(QStringLiteral("--multiple"));
- const bool multipleScreens = QGuiApplication::arguments().contains(QStringLiteral("--multiscreen"));
+ const bool multipleWindows = parser.isSet(multipleOption);
+ const bool multipleScreens = parser.isSet(multipleScreenOption);
QScreen *screen = QGuiApplication::primaryScreen();
@@ -70,7 +89,7 @@ int main(int argc, char *argv[])
QSurfaceFormat format;
format.setDepthBufferSize(16);
- if (QGuiApplication::arguments().contains(QStringLiteral("--multisample")))
+ if (parser.isSet(multipleSampleOption))
format.setSamples(4);
QPoint center = QPoint(screenGeometry.center().x(), screenGeometry.top() + 80);
@@ -136,7 +155,7 @@ int main(int argc, char *argv[])
}
// Quit after 10 seconds. For platforms that do not have windows that are closeable.
- if (QCoreApplication::arguments().contains(QStringLiteral("--timeout")))
+ if (parser.isSet(timeoutOption))
QTimer::singleShot(10000, qGuiApp, &QCoreApplication::quit);
const int exitValue = app.exec();
diff --git a/examples/opengl/qopenglwidget/main.cpp b/examples/opengl/qopenglwidget/main.cpp
index f9b5731b8f..42fc772445 100644
--- a/examples/opengl/qopenglwidget/main.cpp
+++ b/examples/opengl/qopenglwidget/main.cpp
@@ -51,6 +51,8 @@
#include <QApplication>
#include <QMainWindow>
#include <QSurfaceFormat>
+#include <QCommandLineParser>
+#include <QCommandLineOption>
#include "mainwindow.h"
int main( int argc, char ** argv )
@@ -58,12 +60,25 @@ int main( int argc, char ** argv )
Q_INIT_RESOURCE(texture);
QApplication a( argc, argv );
+ QCoreApplication::setApplicationName("Qt QOpenGLWidget Example");
+ QCoreApplication::setOrganizationName("QtProject");
+ QCoreApplication::setApplicationVersion(QT_VERSION_STR);
+ QCommandLineParser parser;
+ parser.setApplicationDescription(QCoreApplication::applicationName());
+ parser.addHelpOption();
+ parser.addVersionOption();
+ QCommandLineOption multipleSampleOption("multisample", "Multisampling");
+ parser.addOption(multipleSampleOption);
+ QCommandLineOption srgbOption("srgb", "Use sRGB Color Space");
+ parser.addOption(srgbOption);
+ parser.process(a);
+
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setStencilBufferSize(8);
- if (QCoreApplication::arguments().contains(QStringLiteral("--srgb")))
+ if (parser.isSet(srgbOption))
format.setColorSpace(QSurfaceFormat::sRGBColorSpace);
- if (QCoreApplication::arguments().contains(QStringLiteral("--multisample")))
+ if (parser.isSet(multipleSampleOption))
format.setSamples(4);
QSurfaceFormat::setDefaultFormat(format);
diff --git a/examples/opengl/threadedqopenglwidget/main.cpp b/examples/opengl/threadedqopenglwidget/main.cpp
index c22cee9228..b9e491040f 100644
--- a/examples/opengl/threadedqopenglwidget/main.cpp
+++ b/examples/opengl/threadedqopenglwidget/main.cpp
@@ -53,6 +53,8 @@
#include <QDesktopWidget>
#include <QSurfaceFormat>
#include <QOpenGLContext>
+#include <QCommandLineParser>
+#include <QCommandLineOption>
#include "mainwindow.h"
#include "glwidget.h"
@@ -67,6 +69,17 @@ int main( int argc, char ** argv )
{
QApplication a( argc, argv );
+ QCoreApplication::setApplicationName("Qt Threaded QOpenGLWidget Example");
+ QCoreApplication::setOrganizationName("QtProject");
+ QCoreApplication::setApplicationVersion(QT_VERSION_STR);
+ QCommandLineParser parser;
+ parser.setApplicationDescription(QCoreApplication::applicationName());
+ parser.addHelpOption();
+ parser.addVersionOption();
+ QCommandLineOption singleOption("single", "Single thread");
+ parser.addOption(singleOption);
+ parser.process(a);
+
QSurfaceFormat format;
format.setDepthBufferSize(16);
QSurfaceFormat::setDefaultFormat(format);
@@ -93,7 +106,7 @@ int main( int argc, char ** argv )
QScopedPointer<MainWindow> mw1;
QScopedPointer<MainWindow> mw2;
- if (!QApplication::arguments().contains(QStringLiteral("--single"))) {
+ if (!parser.isSet(singleOption)) {
if (supportsThreading) {
pos += QPoint(100, 100);
mw1.reset(new MainWindow);
diff --git a/examples/sql/cachedtable/tableeditor.cpp b/examples/sql/cachedtable/tableeditor.cpp
index 71e441486d..95c3047c76 100644
--- a/examples/sql/cachedtable/tableeditor.cpp
+++ b/examples/sql/cachedtable/tableeditor.cpp
@@ -85,9 +85,9 @@ TableEditor::TableEditor(const QString &tableName, QWidget *parent)
//! [2]
//! [3]
- connect(submitButton, SIGNAL(clicked()), this, SLOT(submit()));
- connect(revertButton, SIGNAL(clicked()), model, SLOT(revertAll()));
- connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
+ connect(submitButton, &QPushButton::clicked, this, &TableEditor::submit);
+ connect(revertButton, &QPushButton::clicked, model, &QSqlTableModel::revertAll);
+ connect(quitButton, &QPushButton::clicked, this, &TableEditor::close);
//! [3]
//! [4]
diff --git a/examples/sql/cachedtable/tableeditor.h b/examples/sql/cachedtable/tableeditor.h
index 6544276cbe..727aa88ab3 100644
--- a/examples/sql/cachedtable/tableeditor.h
+++ b/examples/sql/cachedtable/tableeditor.h
@@ -65,7 +65,7 @@ class TableEditor : public QWidget
Q_OBJECT
public:
- explicit TableEditor(const QString &tableName, QWidget *parent = 0);
+ explicit TableEditor(const QString &tableName, QWidget *parent = nullptr);
private slots:
void submit();
diff --git a/examples/sql/connection.h b/examples/sql/connection.h
index 3bedf4b061..482feff5b4 100644
--- a/examples/sql/connection.h
+++ b/examples/sql/connection.h
@@ -70,12 +70,12 @@ static bool createConnection()
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if (!db.open()) {
- QMessageBox::critical(0, qApp->tr("Cannot open database"),
- qApp->tr("Unable to establish a database connection.\n"
- "This example needs SQLite support. Please read "
- "the Qt SQL driver documentation for information how "
- "to build it.\n\n"
- "Click Cancel to exit."), QMessageBox::Cancel);
+ QMessageBox::critical(nullptr, QObject::tr("Cannot open database"),
+ QObject::tr("Unable to establish a database connection.\n"
+ "This example needs SQLite support. Please read "
+ "the Qt SQL driver documentation for information how "
+ "to build it.\n\n"
+ "Click Cancel to exit."), QMessageBox::Cancel);
return false;
}
diff --git a/examples/sql/doc/src/drilldown.qdoc b/examples/sql/doc/src/drilldown.qdoc
index 29c0b613f6..7a8aa2037a 100644
--- a/examples/sql/doc/src/drilldown.qdoc
+++ b/examples/sql/doc/src/drilldown.qdoc
@@ -172,11 +172,20 @@
\snippet drilldown/informationwindow.cpp 4
Finally, we connect the "something's changed" signals in the
- editors to our custom \c enableButtons() slot, enabling the users
- to either submit or revert their changes. We add all the widgets
- into a layout, store the item ID and the name of the displayed
- image file for future reference, and set the window title and
- initial size.
+ editors to our custom \c enableButtons slot, enabling the users
+ to either submit or revert their changes.
+ We need to use lambdas for connecting the \c enableButtons slot
+ because its signature does not match \c QTextEdit::textChanged
+ and \c QComboBox::currentIndexChanged.
+ Since the latter has another overload with the signature
+ \c {const QString &} and the selected signal would be ambiguous,
+ we need to use \c QOverload<int>::of to select a specific overload
+ for \c currentIndexChanged.
+
+ We add all the widgets into a layout, store the item ID and the
+ name of the displayed image file for future reference, and set
+ the window title and initial size.
+
Note that we also set the Qt::Window window flag to indicate that
our widget is in fact a window, with a window system frame and a
@@ -389,19 +398,21 @@
\snippet drilldown/view.cpp 6
The \c showInformation() function is given an \c ImageItem object
- as argument, and starts off by extracting the item's item
- ID. Then it determines if there already is created an information
- window for this location. If it is, and the window is visible, it
- ensures that the window is raised to the top of the widget stack
- and activated. If the window exists but is hidden, calling its \l
- {QWidget::}{show()} slot gives the same result.
+ as argument, and starts off by extracting the item's item ID.
+ Then it determines if there already is created an information
+ window for this location.
If no window for the given location exists, we create one by
passing the item ID, a pointer to the model, and our view as a
parent, to the \c InformationWindow constructor. Note that we
connect the information window's \c imageChanged() signal to \e
this widget's \c updateImage() slot, before we give it a suitable
position and add it to the list of existing windows.
+ If there is a window for the given location, and that window is
+ visible, it ensures that the window is raised to the top of the
+ widget stack and activated. If it is hidden, calling its \l
+ {QWidget::}{show()} slot gives the same result.
+
\snippet drilldown/view.cpp 7
diff --git a/examples/sql/drilldown/imageitem.cpp b/examples/sql/drilldown/imageitem.cpp
index 4e440fc786..04ec614755 100644
--- a/examples/sql/drilldown/imageitem.cpp
+++ b/examples/sql/drilldown/imageitem.cpp
@@ -60,8 +60,8 @@ ImageItem::ImageItem(int id, const QPixmap &pixmap, QGraphicsItem *parent)
timeLine.setDuration(150);
timeLine.setFrameRange(0, 150);
- connect(&timeLine, SIGNAL(frameChanged(int)), this, SLOT(setFrame(int)));
- connect(&timeLine, SIGNAL(finished()), this, SLOT(updateItemPosition()));
+ connect(&timeLine, &QTimeLine::frameChanged, this, &ImageItem::setFrame);
+ connect(&timeLine, &QTimeLine::finished, this, &ImageItem::updateItemPosition);
adjust();
}
@@ -116,7 +116,7 @@ void ImageItem::adjust()
//! [4]
//! [5]
-int ImageItem::id()
+int ImageItem::id() const
{
return recordId;
}
diff --git a/examples/sql/drilldown/imageitem.h b/examples/sql/drilldown/imageitem.h
index 4f773a6dfc..abb9103c7e 100644
--- a/examples/sql/drilldown/imageitem.h
+++ b/examples/sql/drilldown/imageitem.h
@@ -60,10 +60,10 @@ class ImageItem : public QObject, public QGraphicsPixmapItem
Q_OBJECT
public:
- ImageItem(int id, const QPixmap &pixmap, QGraphicsItem *parent = 0);
+ ImageItem(int id, const QPixmap &pixmap, QGraphicsItem *parent = nullptr);
void adjust();
- int id();
+ int id() const;
protected:
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
diff --git a/examples/sql/drilldown/informationwindow.cpp b/examples/sql/drilldown/informationwindow.cpp
index 2536b0ca91..0007432672 100644
--- a/examples/sql/drilldown/informationwindow.cpp
+++ b/examples/sql/drilldown/informationwindow.cpp
@@ -84,10 +84,12 @@ InformationWindow::InformationWindow(int id, QSqlRelationalTableModel *items,
//! [3]
//! [4]
- connect(descriptionEditor, SIGNAL(textChanged()),
- this, SLOT(enableButtons()));
- connect(imageFileEditor, SIGNAL(currentIndexChanged(int)),
- this, SLOT(enableButtons()));
+ connect(descriptionEditor, &QTextEdit::textChanged, [=]() {
+ enableButtons();
+ });
+ connect(imageFileEditor, QOverload<int>::of(&QComboBox::currentIndexChanged), [=]() {
+ enableButtons();
+ });
QFormLayout *formLayout = new QFormLayout;
formLayout->addRow(itemLabel, itemText);
@@ -109,7 +111,7 @@ InformationWindow::InformationWindow(int id, QSqlRelationalTableModel *items,
//! [4]
//! [5]
-int InformationWindow::id()
+int InformationWindow::id() const
{
return itemId;
}
@@ -149,9 +151,9 @@ void InformationWindow::createButtons()
closeButton->setDefault(true);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
- connect(revertButton, SIGNAL(clicked()), this, SLOT(revert()));
- connect(submitButton, SIGNAL(clicked()), this, SLOT(submit()));
+ connect(closeButton, &QPushButton::clicked, this, &InformationWindow::close);
+ connect(revertButton, &QPushButton::clicked, this, &InformationWindow::revert);
+ connect(submitButton, &QPushButton::clicked, this, &InformationWindow::submit);
//! [8]
//! [9]
diff --git a/examples/sql/drilldown/informationwindow.h b/examples/sql/drilldown/informationwindow.h
index 6e87cea65a..653837d722 100644
--- a/examples/sql/drilldown/informationwindow.h
+++ b/examples/sql/drilldown/informationwindow.h
@@ -61,9 +61,9 @@ class InformationWindow : public QDialog
public:
InformationWindow(int id, QSqlRelationalTableModel *items,
- QWidget *parent = 0);
+ QWidget *parent = nullptr);
- int id();
+ int id() const;
signals:
void imageChanged(int id, const QString &fileName);
@@ -83,16 +83,16 @@ private:
int itemId;
QString displayedImage;
- QComboBox *imageFileEditor;
- QLabel *itemText;
- QTextEdit *descriptionEditor;
+ QComboBox *imageFileEditor = nullptr;
+ QLabel *itemText = nullptr;
+ QTextEdit *descriptionEditor = nullptr;
- QPushButton *closeButton;
- QPushButton *submitButton;
- QPushButton *revertButton;
- QDialogButtonBox *buttonBox;
+ QPushButton *closeButton = nullptr;
+ QPushButton *submitButton = nullptr;
+ QPushButton *revertButton = nullptr;
+ QDialogButtonBox *buttonBox = nullptr;
- QDataWidgetMapper *mapper;
+ QDataWidgetMapper *mapper = nullptr;
};
//! [2]
diff --git a/examples/sql/drilldown/main.cpp b/examples/sql/drilldown/main.cpp
index 3465d11b4d..db3320de48 100644
--- a/examples/sql/drilldown/main.cpp
+++ b/examples/sql/drilldown/main.cpp
@@ -48,10 +48,13 @@
**
****************************************************************************/
-#include <QtWidgets>
-
-#include "../connection.h"
#include "view.h"
+#include "../connection.h"
+
+#include <QApplication>
+
+#include <stdlib.h>
+
int main(int argc, char *argv[])
{
@@ -60,7 +63,7 @@ int main(int argc, char *argv[])
QApplication app(argc, argv);
if (!createConnection())
- return 1;
+ return EXIT_FAILURE;
View view("items", "images");
view.show();
diff --git a/examples/sql/drilldown/view.cpp b/examples/sql/drilldown/view.cpp
index fc05d2fcaf..13e9310061 100644
--- a/examples/sql/drilldown/view.cpp
+++ b/examples/sql/drilldown/view.cpp
@@ -89,8 +89,6 @@ void View::addItems()
int topMargin = 40;
for (int i = 0; i < itemCount; i++) {
- ImageItem *image;
- QGraphicsTextItem *label;
QSqlRecord record = itemTable->record(i);
int id = record.value("id").toInt();
@@ -101,12 +99,12 @@ void View::addItems()
int x = ((i % 2) * imageOffset) + leftMargin + columnOffset;
int y = ((i / 2) * imageOffset) + topMargin;
- image = new ImageItem(id, QPixmap(":/" + file));
+ ImageItem *image = new ImageItem(id, QPixmap(":/" + file));
image->setData(0, i);
image->setPos(x, y);
scene->addItem(image);
- label = scene->addText(item);
+ QGraphicsTextItem *label = scene->addText(item);
label->setDefaultTextColor(QColor("#d7d6d5"));
QPointF labelOffset((120 - label->boundingRect().width()) / 2, 120.0);
label->setPos(QPointF(x, y) + labelOffset);
@@ -133,22 +131,22 @@ void View::showInformation(ImageItem *image)
return;
InformationWindow *window = findWindow(id);
- if (window && window->isVisible()) {
- window->raise();
- window->activateWindow();
- } else if (window && !window->isVisible()) {
- window->show();
- } else {
- InformationWindow *window;
+ if (!window) {
window = new InformationWindow(id, itemTable, this);
- connect(window, SIGNAL(imageChanged(int,QString)),
- this, SLOT(updateImage(int,QString)));
+ connect(window, QOverload<int,const QString &>::of(&InformationWindow::imageChanged),
+ this, QOverload<int,const QString &>::of(&View::updateImage));
window->move(pos() + QPoint(20, 40));
window->show();
informationWindows.append(window);
}
+
+ if (window->isVisible()) {
+ window->raise();
+ window->activateWindow();
+ } else
+ window->show();
}
//! [6]
@@ -172,19 +170,13 @@ void View::updateImage(int id, const QString &fileName)
//! [7]
//! [8]
-InformationWindow* View::findWindow(int id)
+InformationWindow *View::findWindow(int id) const
{
- QList<InformationWindow*>::iterator i, beginning, end;
-
- beginning = informationWindows.begin();
- end = informationWindows.end();
-
- for (i = beginning; i != end; ++i) {
- InformationWindow *window = (*i);
+ for (auto window : informationWindows) {
if (window && (window->id() == id))
return window;
}
- return 0;
+ return nullptr;
}
//! [8]
diff --git a/examples/sql/drilldown/view.h b/examples/sql/drilldown/view.h
index 9d6ef0e853..5afa1a25e9 100644
--- a/examples/sql/drilldown/view.h
+++ b/examples/sql/drilldown/view.h
@@ -63,7 +63,7 @@ class View : public QGraphicsView
Q_OBJECT
public:
- View(const QString &items, const QString &images, QWidget *parent = 0);
+ View(const QString &items, const QString &images, QWidget *parent = nullptr);
protected:
void mouseReleaseEvent(QMouseEvent *event) override;
@@ -77,7 +77,7 @@ private slots:
//! [2]
private:
void addItems();
- InformationWindow* findWindow(int id);
+ InformationWindow *findWindow(int id) const;
void showInformation(ImageItem *image);
QGraphicsScene *scene;
diff --git a/examples/sql/masterdetail/database.h b/examples/sql/masterdetail/database.h
index 3139deb0b2..9cbca6f749 100644
--- a/examples/sql/masterdetail/database.h
+++ b/examples/sql/masterdetail/database.h
@@ -61,12 +61,12 @@ static bool createConnection()
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if (!db.open()) {
- QMessageBox::critical(0, qApp->tr("Cannot open database"),
- qApp->tr("Unable to establish a database connection.\n"
- "This example needs SQLite support. Please read "
- "the Qt SQL driver documentation for information how "
- "to build it.\n\n"
- "Click Cancel to exit."), QMessageBox::Cancel);
+ QMessageBox::critical(nullptr, QObject::tr("Cannot open database"),
+ QObject::tr("Unable to establish a database connection.\n"
+ "This example needs SQLite support. Please read "
+ "the Qt SQL driver documentation for information how "
+ "to build it.\n\n"
+ "Click Cancel to exit."), QMessageBox::Cancel);
return false;
}
diff --git a/examples/sql/masterdetail/dialog.cpp b/examples/sql/masterdetail/dialog.cpp
index 5bb213230e..bb1812eace 100644
--- a/examples/sql/masterdetail/dialog.cpp
+++ b/examples/sql/masterdetail/dialog.cpp
@@ -155,12 +155,12 @@ int Dialog::addNewAlbum(const QString &title, int artistId)
return id;
}
-void Dialog::addTracks(int albumId, QStringList tracks)
+void Dialog::addTracks(int albumId, const QStringList &tracks)
{
QDomElement albumNode = albumDetails.createElement("album");
albumNode.setAttribute("id", albumId);
- for (int i = 0; i < tracks.count(); i++) {
+ for (int i = 0; i < tracks.count(); ++i) {
QString trackNumber = QString::number(i);
if (i < 10)
trackNumber.prepend('0');
@@ -254,9 +254,9 @@ QDialogButtonBox *Dialog::createButtons()
closeButton->setDefault(true);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
- connect(revertButton, SIGNAL(clicked()), this, SLOT(revert()));
- connect(submitButton, SIGNAL(clicked()), this, SLOT(submit()));
+ connect(closeButton, &QPushButton::clicked, this, &Dialog::close);
+ connect(revertButton, &QPushButton::clicked, this, &Dialog::revert);
+ connect(submitButton, &QPushButton::clicked, this, &Dialog::submit);
QDialogButtonBox *buttonBox = new QDialogButtonBox;
buttonBox->addButton(submitButton, QDialogButtonBox::ResetRole);
@@ -270,7 +270,7 @@ QModelIndex Dialog::indexOfArtist(const QString &artist)
{
QSqlTableModel *artistModel = model->relationModel(2);
- for (int i = 0; i < artistModel->rowCount(); i++) {
+ for (int i = 0; i < artistModel->rowCount(); ++i) {
QSqlRecord record = artistModel->record(i);
if (record.value("artist") == artist)
return artistModel->index(i, 1);
diff --git a/examples/sql/masterdetail/dialog.h b/examples/sql/masterdetail/dialog.h
index 1789207d8d..31c4d8552c 100644
--- a/examples/sql/masterdetail/dialog.h
+++ b/examples/sql/masterdetail/dialog.h
@@ -61,7 +61,7 @@ class Dialog : public QDialog
public:
Dialog(QSqlRelationalTableModel *albums, QDomDocument details,
- QFile *output, QWidget *parent = 0);
+ QFile *output, QWidget *parent = nullptr);
private slots:
void revert();
@@ -70,12 +70,12 @@ private slots:
private:
int addNewAlbum(const QString &title, int artistId);
int addNewArtist(const QString &name);
- void addTracks(int albumId, QStringList tracks);
+ void addTracks(int albumId, const QStringList &tracks);
QDialogButtonBox *createButtons();
QGroupBox *createInputWidgets();
int findArtistId(const QString &artist);
- int generateAlbumId();
- int generateArtistId();
+ static int generateAlbumId();
+ static int generateArtistId();
void increaseAlbumCount(QModelIndex artistIndex);
QModelIndex indexOfArtist(const QString &artist);
diff --git a/examples/sql/masterdetail/main.cpp b/examples/sql/masterdetail/main.cpp
index cc1a1c4a21..9a4172e55f 100644
--- a/examples/sql/masterdetail/main.cpp
+++ b/examples/sql/masterdetail/main.cpp
@@ -48,11 +48,14 @@
**
****************************************************************************/
-#include <QtWidgets>
-
#include "database.h"
#include "mainwindow.h"
+#include <QApplication>
+#include <QFile>
+
+#include <stdlib.h>
+
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(masterdetail);
@@ -60,10 +63,10 @@ int main(int argc, char *argv[])
QApplication app(argc, argv);
if (!createConnection())
- return 1;
+ return EXIT_FAILURE;
- QFile *albumDetails = new QFile("albumdetails.xml");
- MainWindow window("artists", "albums", albumDetails);
+ QFile albumDetails("albumdetails.xml");
+ MainWindow window("artists", "albums", &albumDetails);
window.show();
return app.exec();
}
diff --git a/examples/sql/masterdetail/mainwindow.cpp b/examples/sql/masterdetail/mainwindow.cpp
index 9fbc4c43a4..7f3479619a 100644
--- a/examples/sql/masterdetail/mainwindow.cpp
+++ b/examples/sql/masterdetail/mainwindow.cpp
@@ -78,10 +78,10 @@ MainWindow::MainWindow(const QString &artistTable, const QString &albumTable,
uniqueAlbumId = model->rowCount();
uniqueArtistId = artistView->count();
- connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(updateHeader(QModelIndex,int,int)));
- connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(updateHeader(QModelIndex,int,int)));
+ connect(model, &QSqlRelationalTableModel::rowsInserted,
+ this, &MainWindow::updateHeader);
+ connect(model, &QSqlRelationalTableModel::rowsRemoved,
+ this, &MainWindow::updateHeader);
QGridLayout *layout = new QGridLayout;
layout->addWidget(artists, 0, 0);
@@ -145,7 +145,7 @@ void MainWindow::showAlbumDetails(QModelIndex index)
titleLabel->show();
QDomNodeList albums = albumData.elementsByTagName("album");
- for (int i = 0; i < albums.count(); i++) {
+ for (int i = 0; i < albums.count(); ++i) {
QDomNode album = albums.item(i);
if (album.toElement().attribute("id") == albumId) {
getTrackList(album.toElement());
@@ -164,9 +164,9 @@ void MainWindow::getTrackList(QDomNode album)
QDomNode track;
QString trackNumber;
- for (int j = 0; j < tracks.count(); j++) {
+ for (int i = 0; i < tracks.count(); ++i) {
- track = tracks.item(j);
+ track = tracks.item(i);
trackNumber = track.toElement().attribute("number");
QListWidgetItem *item = new QListWidgetItem(trackList);
@@ -222,7 +222,7 @@ void MainWindow::removeAlbumFromFile(int id)
QDomNodeList albums = albumData.elementsByTagName("album");
- for (int i = 0; i < albums.count(); i++) {
+ for (int i = 0; i < albums.count(); ++i) {
QDomNode node = albums.item(i);
if (node.toElement().attribute("id").toInt() == id) {
albumData.elementsByTagName("archive").item(0).removeChild(node);
@@ -283,8 +283,8 @@ QGroupBox* MainWindow::createArtistGroupBox()
artistView->setModel(model->relationModel(2));
artistView->setModelColumn(1);
- connect(artistView, SIGNAL(currentIndexChanged(int)),
- this, SLOT(changeArtist(int)));
+ connect(artistView, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, &MainWindow::changeArtist);
QGroupBox *box = new QGroupBox(tr("Artist"));
@@ -314,10 +314,10 @@ QGroupBox* MainWindow::createAlbumGroupBox()
locale.setNumberOptions(QLocale::OmitGroupSeparator);
albumView->setLocale(locale);
- connect(albumView, SIGNAL(clicked(QModelIndex)),
- this, SLOT(showAlbumDetails(QModelIndex)));
- connect(albumView, SIGNAL(activated(QModelIndex)),
- this, SLOT(showAlbumDetails(QModelIndex)));
+ connect(albumView, &QTableView::clicked,
+ this, &MainWindow::showAlbumDetails);
+ connect(albumView, &QTableView::activated,
+ this, &MainWindow::showAlbumDetails);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(albumView, 0, 0);
@@ -383,11 +383,16 @@ void MainWindow::createMenuBar()
helpMenu->addAction(aboutAction);
helpMenu->addAction(aboutQtAction);
- connect(addAction, SIGNAL(triggered(bool)), this, SLOT(addAlbum()));
- connect(deleteAction, SIGNAL(triggered(bool)), this, SLOT(deleteAlbum()));
- connect(quitAction, SIGNAL(triggered(bool)), this, SLOT(close()));
- connect(aboutAction, SIGNAL(triggered(bool)), this, SLOT(about()));
- connect(aboutQtAction, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt()));
+ connect(addAction, &QAction::triggered,
+ this, &MainWindow::addAlbum);
+ connect(deleteAction, &QAction::triggered,
+ this, &MainWindow::deleteAlbum);
+ connect(quitAction, &QAction::triggered,
+ this, &MainWindow::close);
+ connect(aboutAction, &QAction::triggered,
+ this, &MainWindow::about);
+ connect(aboutQtAction, &QAction::triggered,
+ qApp, &QApplication::aboutQt);
}
void MainWindow::showImageLabel()
diff --git a/examples/sql/masterdetail/mainwindow.h b/examples/sql/masterdetail/mainwindow.h
index be3c6c94f4..dc6d8d1613 100644
--- a/examples/sql/masterdetail/mainwindow.h
+++ b/examples/sql/masterdetail/mainwindow.h
@@ -71,7 +71,7 @@ class MainWindow : public QMainWindow
public:
MainWindow(const QString &artistTable, const QString &albumTable,
- QFile *albumDetails, QWidget *parent = 0);
+ QFile *albumDetails, QWidget *parent = nullptr);
private slots:
void about();
diff --git a/examples/sql/querymodel/customsqlmodel.h b/examples/sql/querymodel/customsqlmodel.h
index 5d2f625665..462d2ab822 100644
--- a/examples/sql/querymodel/customsqlmodel.h
+++ b/examples/sql/querymodel/customsqlmodel.h
@@ -59,7 +59,7 @@ class CustomSqlModel : public QSqlQueryModel
Q_OBJECT
public:
- CustomSqlModel(QObject *parent = 0);
+ CustomSqlModel(QObject *parent = nullptr);
QVariant data(const QModelIndex &item, int role) const override;
};
diff --git a/examples/sql/querymodel/editablesqlmodel.h b/examples/sql/querymodel/editablesqlmodel.h
index 1341dd372a..e8caad2765 100644
--- a/examples/sql/querymodel/editablesqlmodel.h
+++ b/examples/sql/querymodel/editablesqlmodel.h
@@ -58,7 +58,7 @@ class EditableSqlModel : public QSqlQueryModel
Q_OBJECT
public:
- EditableSqlModel(QObject *parent = 0);
+ EditableSqlModel(QObject *parent = nullptr);
Qt::ItemFlags flags(const QModelIndex &index) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role) override;
diff --git a/examples/sql/querymodel/main.cpp b/examples/sql/querymodel/main.cpp
index 83804682f9..da19939dd8 100644
--- a/examples/sql/querymodel/main.cpp
+++ b/examples/sql/querymodel/main.cpp
@@ -48,12 +48,15 @@
**
****************************************************************************/
-#include <QtWidgets>
-
#include "../connection.h"
#include "customsqlmodel.h"
#include "editablesqlmodel.h"
+#include <QApplication>
+#include <QTableView>
+
+#include <stdlib.h>
+
void initializeModel(QSqlQueryModel *model)
{
model->setQuery("select * from person");
@@ -80,7 +83,7 @@ int main(int argc, char *argv[])
{
QApplication app(argc, argv);
if (!createConnection())
- return 1;
+ return EXIT_FAILURE;
QSqlQueryModel plainModel;
EditableSqlModel editableModel;
diff --git a/examples/sql/relationaltablemodel/relationaltablemodel.cpp b/examples/sql/relationaltablemodel/relationaltablemodel.cpp
index 5292256cd9..c3c7d48d70 100644
--- a/examples/sql/relationaltablemodel/relationaltablemodel.cpp
+++ b/examples/sql/relationaltablemodel/relationaltablemodel.cpp
@@ -110,7 +110,8 @@ int main(int argc, char *argv[])
{
QApplication app(argc, argv);
if (!createConnection())
- return 1;
+ return EXIT_FAILURE;
+
createRelationalTables();
QSqlRelationalTableModel model;
diff --git a/examples/sql/sqlbrowser/browser.cpp b/examples/sql/sqlbrowser/browser.cpp
index d86c54404d..b05cf52099 100644
--- a/examples/sql/sqlbrowser/browser.cpp
+++ b/examples/sql/sqlbrowser/browser.cpp
@@ -165,11 +165,12 @@ void Browser::showTable(const QString &t)
model->select();
if (model->lastError().type() != QSqlError::NoError)
emit statusMessage(model->lastError().text());
+
table->setModel(model);
table->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed);
+ connect(table->selectionModel(), &QItemSelectionModel::currentRowChanged,
+ this, &Browser::currentChanged);
- connect(table->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- this, SLOT(currentChanged()));
updateActions();
}
@@ -189,7 +190,6 @@ void Browser::showMetaData(const QString &t)
model->setHeaderData(5, Qt::Horizontal, "AutoValue");
model->setHeaderData(6, Qt::Horizontal, "DefaultValue");
-
for (int i = 0; i < rec.count(); ++i) {
QSqlField fld = rec.field(i);
model->setData(model->index(i, 0), fld.name());
diff --git a/examples/sql/sqlbrowser/browser.h b/examples/sql/sqlbrowser/browser.h
index fef410778b..3f98f487c3 100644
--- a/examples/sql/sqlbrowser/browser.h
+++ b/examples/sql/sqlbrowser/browser.h
@@ -65,7 +65,7 @@ class Browser: public QWidget, private Ui::Browser
{
Q_OBJECT
public:
- Browser(QWidget *parent = 0);
+ Browser(QWidget *parent = nullptr);
virtual ~Browser();
QSqlError addConnection(const QString &driver, const QString &dbName, const QString &host,
@@ -116,7 +116,9 @@ class CustomModel: public QSqlTableModel
{
Q_OBJECT
public:
- explicit CustomModel(QObject *parent = 0, QSqlDatabase db = QSqlDatabase()):QSqlTableModel(parent, db) {}
+ explicit CustomModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase())
+ : QSqlTableModel(parent, db) {}
+
QVariant data(const QModelIndex &idx, int role) const override
{
if (role == Qt::BackgroundRole && isDirty(idx))
diff --git a/examples/sql/sqlbrowser/connectionwidget.cpp b/examples/sql/sqlbrowser/connectionwidget.cpp
index 888579c9af..658cfb77dc 100644
--- a/examples/sql/sqlbrowser/connectionwidget.cpp
+++ b/examples/sql/sqlbrowser/connectionwidget.cpp
@@ -63,8 +63,8 @@ ConnectionWidget::ConnectionWidget(QWidget *parent)
tree->header()->setSectionResizeMode(QHeaderView::Stretch);
QAction *refreshAction = new QAction(tr("Refresh"), tree);
metaDataAction = new QAction(tr("Show Schema"), tree);
- connect(refreshAction, SIGNAL(triggered()), SLOT(refresh()));
- connect(metaDataAction, SIGNAL(triggered()), SLOT(showMetaData()));
+ connect(refreshAction, &QAction::triggered, this, &ConnectionWidget::refresh);
+ connect(metaDataAction, &QAction::triggered, this, &ConnectionWidget::showMetaData);
tree->addAction(refreshAction);
tree->addAction(metaDataAction);
tree->setContextMenuPolicy(Qt::ActionsContextMenu);
@@ -146,7 +146,6 @@ void ConnectionWidget::setActive(QTreeWidgetItem *item)
void ConnectionWidget::on_tree_itemActivated(QTreeWidgetItem *item, int /* column */)
{
-
if (!item)
return;
diff --git a/examples/sql/sqlbrowser/connectionwidget.h b/examples/sql/sqlbrowser/connectionwidget.h
index 8b8e3a9a62..a805765f69 100644
--- a/examples/sql/sqlbrowser/connectionwidget.h
+++ b/examples/sql/sqlbrowser/connectionwidget.h
@@ -62,7 +62,7 @@ class ConnectionWidget: public QWidget
{
Q_OBJECT
public:
- ConnectionWidget(QWidget *parent = 0);
+ ConnectionWidget(QWidget *parent = nullptr);
virtual ~ConnectionWidget();
QSqlDatabase currentDatabase() const;
diff --git a/examples/sql/sqlbrowser/main.cpp b/examples/sql/sqlbrowser/main.cpp
index 002dbc3242..ea4649b68d 100644
--- a/examples/sql/sqlbrowser/main.cpp
+++ b/examples/sql/sqlbrowser/main.cpp
@@ -80,16 +80,18 @@ int main(int argc, char *argv[])
mainWin.setCentralWidget(&browser);
QMenu *fileMenu = mainWin.menuBar()->addMenu(QObject::tr("&File"));
- fileMenu->addAction(QObject::tr("Add &Connection..."), &browser, SLOT(addConnection()));
+ fileMenu->addAction(QObject::tr("Add &Connection..."),
+ [&]() { browser.addConnection(); });
fileMenu->addSeparator();
- fileMenu->addAction(QObject::tr("&Quit"), &app, SLOT(quit()));
+ fileMenu->addAction(QObject::tr("&Quit"), []() { qApp->quit(); });
QMenu *helpMenu = mainWin.menuBar()->addMenu(QObject::tr("&Help"));
- helpMenu->addAction(QObject::tr("About"), &browser, SLOT(about()));
- helpMenu->addAction(QObject::tr("About Qt"), qApp, SLOT(aboutQt()));
+ helpMenu->addAction(QObject::tr("About"), [&]() { browser.about(); });
+ helpMenu->addAction(QObject::tr("About Qt"), []() { qApp->aboutQt(); });
- QObject::connect(&browser, SIGNAL(statusMessage(QString)),
- mainWin.statusBar(), SLOT(showMessage(QString)));
+ QObject::connect(&browser, &Browser::statusMessage, [&mainWin](const QString &text) {
+ mainWin.statusBar()->showMessage(text);
+ });
addConnectionsFromCommandline(app.arguments(), &browser);
mainWin.show();
diff --git a/examples/sql/sqlbrowser/qsqlconnectiondialog.h b/examples/sql/sqlbrowser/qsqlconnectiondialog.h
index d43955acdc..fc998d7ee9 100644
--- a/examples/sql/sqlbrowser/qsqlconnectiondialog.h
+++ b/examples/sql/sqlbrowser/qsqlconnectiondialog.h
@@ -60,7 +60,7 @@ class QSqlConnectionDialog: public QDialog
{
Q_OBJECT
public:
- QSqlConnectionDialog(QWidget *parent = 0);
+ QSqlConnectionDialog(QWidget *parent = nullptr);
~QSqlConnectionDialog();
QString driverName() const;
diff --git a/examples/sql/sqlwidgetmapper/window.cpp b/examples/sql/sqlwidgetmapper/window.cpp
index 21ce152169..b6946e2386 100644
--- a/examples/sql/sqlwidgetmapper/window.cpp
+++ b/examples/sql/sqlwidgetmapper/window.cpp
@@ -87,12 +87,12 @@ Window::Window(QWidget *parent)
//! [Set up the mapper]
//! [Set up connections and layouts]
- connect(previousButton, SIGNAL(clicked()),
- mapper, SLOT(toPrevious()));
- connect(nextButton, SIGNAL(clicked()),
- mapper, SLOT(toNext()));
- connect(mapper, SIGNAL(currentIndexChanged(int)),
- this, SLOT(updateButtons(int)));
+ connect(previousButton, &QPushButton::clicked,
+ mapper, &QDataWidgetMapper::toPrevious);
+ connect(nextButton, &QPushButton::clicked,
+ mapper, &QDataWidgetMapper::toNext);
+ connect(mapper, &QDataWidgetMapper::currentIndexChanged,
+ this, &Window::updateButtons);
QGridLayout *layout = new QGridLayout();
layout->addWidget(nameLabel, 0, 0, 1, 1);
diff --git a/examples/sql/sqlwidgetmapper/window.h b/examples/sql/sqlwidgetmapper/window.h
index bff074d954..b336997360 100644
--- a/examples/sql/sqlwidgetmapper/window.h
+++ b/examples/sql/sqlwidgetmapper/window.h
@@ -72,7 +72,7 @@ class Window : public QWidget
Q_OBJECT
public:
- Window(QWidget *parent = 0);
+ Window(QWidget *parent = nullptr);
private slots:
void updateButtons(int row);
diff --git a/examples/sql/tablemodel/tablemodel.cpp b/examples/sql/tablemodel/tablemodel.cpp
index c22e25cbef..a6e0341c23 100644
--- a/examples/sql/tablemodel/tablemodel.cpp
+++ b/examples/sql/tablemodel/tablemodel.cpp
@@ -47,11 +47,13 @@
** $QT_END_LICENSE$
**
****************************************************************************/
+#include "../connection.h"
-#include <QtWidgets>
-#include <QtSql>
+#include <QApplication>
+#include <QSqlTableModel>
+#include <QTableView>
-#include "../connection.h"
+#include <stdlib.h>
void initializeModel(QSqlTableModel *model)
{
@@ -76,7 +78,7 @@ int main(int argc, char *argv[])
{
QApplication app(argc, argv);
if (!createConnection())
- return 1;
+ return EXIT_FAILURE;
QSqlTableModel model;
diff --git a/examples/widgets/dialogs/dialogs.pro b/examples/widgets/dialogs/dialogs.pro
index 82e814dcb0..a29903938e 100644
--- a/examples/widgets/dialogs/dialogs.pro
+++ b/examples/widgets/dialogs/dialogs.pro
@@ -14,4 +14,3 @@ SUBDIRS = classwizard \
!qtConfig(wizard) {
SUBDIRS -= trivialwizard licensewizard classwizard
}
-wince: SUBDIRS += sipdialog
diff --git a/examples/widgets/itemviews/storageview/main.cpp b/examples/widgets/itemviews/storageview/main.cpp
index c8057186fc..f349e58fad 100644
--- a/examples/widgets/itemviews/storageview/main.cpp
+++ b/examples/widgets/itemviews/storageview/main.cpp
@@ -51,6 +51,7 @@
#include <QtWidgets/QApplication>
#include <QtWidgets/QHeaderView>
+#include <QtWidgets/QShortcut>
#include <QtWidgets/QTreeView>
#include "storagemodel.h"
@@ -60,9 +61,16 @@ int main(int argc, char *argv[])
QApplication a(argc, argv);
QTreeView view;
- view.setModel(new StorageModel(&view));
view.resize(640, 480);
+ view.setWindowTitle("Storage View");
view.setSelectionBehavior(QAbstractItemView::SelectRows);
+
+ StorageModel *model = new StorageModel(&view);
+ model->refresh();
+ QShortcut *refreshShortcut = new QShortcut(Qt::CTRL + Qt::Key_R, &view);
+ QObject::connect(refreshShortcut, &QShortcut::activated, model, &StorageModel::refresh);
+ view.setModel(model);
+
int columnCount = view.model()->columnCount();
for (int c = 0; c < columnCount; ++c)
view.resizeColumnToContents(c);
diff --git a/examples/widgets/itemviews/storageview/storagemodel.cpp b/examples/widgets/itemviews/storageview/storagemodel.cpp
index 1395c9f208..063f126d86 100644
--- a/examples/widgets/itemviews/storageview/storagemodel.cpp
+++ b/examples/widgets/itemviews/storageview/storagemodel.cpp
@@ -54,14 +54,27 @@
#include <QDir>
#include <QLocale>
#include <qmath.h>
+#include <algorithm>
#include <cmath>
StorageModel::StorageModel(QObject *parent) :
- QAbstractTableModel(parent),
- m_volumes(QStorageInfo::mountedVolumes())
+ QAbstractTableModel(parent)
{
}
+void StorageModel::refresh()
+{
+ beginResetModel();
+ m_volumes = QStorageInfo::mountedVolumes();
+ std::sort(m_volumes.begin(), m_volumes.end(),
+ [](const QStorageInfo &st1, const QStorageInfo &st2) {
+ static const QString rootSortString = QStringLiteral(" ");
+ return (st1.isRoot() ? rootSortString : st1.rootPath())
+ < (st2.isRoot() ? rootSortString : st2.rootPath());
+ });
+ endResetModel();
+}
+
int StorageModel::columnCount(const QModelIndex &/*parent*/) const
{
return ColumnCount;
@@ -74,6 +87,22 @@ int StorageModel::rowCount(const QModelIndex &parent) const
return m_volumes.count();
}
+Qt::ItemFlags StorageModel::flags(const QModelIndex &index) const
+{
+ Qt::ItemFlags result = QAbstractTableModel::flags(index);
+ switch (index.column()) {
+ case ColumnAvailable:
+ case ColumnIsReady:
+ case ColumnIsReadOnly:
+ case ColumnIsValid:
+ result |= Qt::ItemIsUserCheckable;
+ break;
+ default:
+ break;
+ }
+ return result;
+}
+
QVariant StorageModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
@@ -96,6 +125,12 @@ QVariant StorageModel::data(const QModelIndex &index, int role) const
return QLocale().formattedDataSize(volume.bytesFree());
case ColumnAvailable:
return QLocale().formattedDataSize(volume.bytesAvailable());
+ default:
+ break;
+ }
+ } else if (role == Qt::CheckStateRole) {
+ const QStorageInfo &volume = m_volumes.at(index.row());
+ switch (index.column()) {
case ColumnIsReady:
return volume.isReady();
case ColumnIsReadOnly:
@@ -105,6 +140,16 @@ QVariant StorageModel::data(const QModelIndex &index, int role) const
default:
break;
}
+ } else if (role == Qt::TextAlignmentRole) {
+ switch (index.column()) {
+ case ColumnTotal:
+ case ColumnFree:
+ case ColumnAvailable:
+ return Qt::AlignTrailing;
+ default:
+ break;
+ }
+ return Qt::AlignLeading;
} else if (role == Qt::ToolTipRole) {
QLocale locale;
const QStorageInfo &volume = m_volumes.at(index.row());
@@ -147,13 +192,13 @@ QVariant StorageModel::headerData(int section, Qt::Orientation orientation, int
switch (section) {
case ColumnRootPath:
- return tr("Root path");
+ return tr("Root Path");
case ColumnName:
return tr("Volume Name");
case ColumnDevice:
return tr("Device");
case ColumnFileSystemName:
- return tr("File system");
+ return tr("File System");
case ColumnTotal:
return tr("Total");
case ColumnFree:
diff --git a/examples/widgets/itemviews/storageview/storagemodel.h b/examples/widgets/itemviews/storageview/storagemodel.h
index 2b37414d8d..787b2f04de 100644
--- a/examples/widgets/itemviews/storageview/storagemodel.h
+++ b/examples/widgets/itemviews/storageview/storagemodel.h
@@ -74,13 +74,17 @@ public:
ColumnCount
};
- explicit StorageModel(QObject *parent = 0);
+ explicit StorageModel(QObject *parent = nullptr);
- int columnCount(const QModelIndex &parent) const;
- int rowCount(const QModelIndex &parent) const;
+ int columnCount(const QModelIndex &parent) const override;
+ int rowCount(const QModelIndex &parent) const override;
- QVariant data(const QModelIndex &index, int role) const;
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
+ QVariant data(const QModelIndex &index, int role) const override;
+ Qt::ItemFlags flags(const QModelIndex &index) const override;
+ QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
+
+public slots:
+ void refresh();
private:
QList<QStorageInfo> m_volumes;