summaryrefslogtreecommitdiffstats
path: root/examples/corelib
diff options
context:
space:
mode:
Diffstat (limited to 'examples/corelib')
-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/corelib/json/savegame/character.cpp28
-rw-r--r--examples/corelib/json/savegame/character.h6
-rw-r--r--examples/corelib/json/savegame/doc/src/savegame.qdoc37
-rw-r--r--examples/corelib/json/savegame/game.cpp86
-rw-r--r--examples/corelib/json/savegame/game.h12
-rw-r--r--examples/corelib/json/savegame/level.cpp44
-rw-r--r--examples/corelib/json/savegame/level.h16
-rw-r--r--examples/corelib/json/savegame/main.cpp28
-rw-r--r--examples/corelib/threads/queuedcustomtype/main.cpp1
-rw-r--r--examples/corelib/threads/queuedcustomtype/renderthread.cpp6
-rw-r--r--examples/corelib/threads/semaphores/semaphores.cpp3
-rw-r--r--examples/corelib/threads/waitconditions/waitconditions.cpp4
-rw-r--r--examples/corelib/tools/contiguouscache/randomlistmodel.cpp3
19 files changed, 243 insertions, 154 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..be8d4750d6 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::global()->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/corelib/json/savegame/character.cpp b/examples/corelib/json/savegame/character.cpp
index 20bbc34961..046cde3091 100644
--- a/examples/corelib/json/savegame/character.cpp
+++ b/examples/corelib/json/savegame/character.cpp
@@ -50,12 +50,17 @@
#include "character.h"
+#include <QMetaEnum>
+#include <QTextStream>
+
Character::Character() :
mLevel(0),
mClassType(Warrior) {
}
-Character::Character(const QString &name, int level, Character::ClassType classType) :
+Character::Character(const QString &name,
+ int level,
+ Character::ClassType classType) :
mName(name),
mLevel(level),
mClassType(classType)
@@ -95,9 +100,14 @@ void Character::setClassType(Character::ClassType classType)
//! [0]
void Character::read(const QJsonObject &json)
{
- mName = json["name"].toString();
- mLevel = json["level"].toDouble();
- mClassType = ClassType(qRound(json["classType"].toDouble()));
+ if (json.contains("name") && json["name"].isString())
+ mName = json["name"].toString();
+
+ if (json.contains("level") && json["level"].isDouble())
+ mLevel = json["level"].toInt();
+
+ if (json.contains("classType") && json["classType"].isDouble())
+ mClassType = ClassType(json["classType"].toInt());
}
//! [0]
@@ -109,3 +119,13 @@ void Character::write(QJsonObject &json) const
json["classType"] = mClassType;
}
//! [1]
+
+void Character::print(int indentation) const
+{
+ const QString indent(indentation * 2, ' ');
+ QTextStream(stdout) << indent << "Name:\t" << mName << "\n";
+ QTextStream(stdout) << indent << "Level:\t" << mLevel << "\n";
+
+ QString className = QMetaEnum::fromType<ClassType>().valueToKey(mClassType);
+ QTextStream(stdout) << indent << "Class:\t" << className << "\n";
+}
diff --git a/examples/corelib/json/savegame/character.h b/examples/corelib/json/savegame/character.h
index 740496822c..cbf06d7fd6 100644
--- a/examples/corelib/json/savegame/character.h
+++ b/examples/corelib/json/savegame/character.h
@@ -52,15 +52,19 @@
#define CHARACTER_H
#include <QJsonObject>
+#include <QObject>
#include <QString>
//! [0]
class Character
{
+ Q_GADGET;
+
public:
enum ClassType {
Warrior, Mage, Archer
};
+ Q_ENUM(ClassType)
Character();
Character(const QString &name, int level, ClassType classType);
@@ -76,6 +80,8 @@ public:
void read(const QJsonObject &json);
void write(QJsonObject &json) const;
+
+ void print(int indentation = 0) const;
private:
QString mName;
int mLevel;
diff --git a/examples/corelib/json/savegame/doc/src/savegame.qdoc b/examples/corelib/json/savegame/doc/src/savegame.qdoc
index fec5fe8e5d..06e70680c6 100644
--- a/examples/corelib/json/savegame/doc/src/savegame.qdoc
+++ b/examples/corelib/json/savegame/doc/src/savegame.qdoc
@@ -61,8 +61,8 @@
QJsonObject argument. You can use either \l QJsonObject::operator[]() or
QJsonObject::value() to access values within the JSON object; both are
const functions and return QJsonValue::Undefined if the key is invalid. We
- could check if the keys are valid before attempting to read them with
- QJsonObject::contains(), but we assume that they are.
+ check if the keys are valid before attempting to read them with
+ QJsonObject::contains().
\snippet json/savegame/character.cpp 1
@@ -77,7 +77,7 @@
\snippet json/savegame/level.h 0
We want to have several levels in our game, each with several NPCs, so we
- keep a QList of Character objects. We also provide the familiar read() and
+ keep a QVector of Character objects. We also provide the familiar read() and
write() functions.
\snippet json/savegame/level.cpp 0
@@ -86,7 +86,7 @@
case, we construct a QJsonArray from the value associated with the key
\c "npcs". Then, for each QJsonValue element in the array, we call
toObject() to get the Character's JSON object. The Character object can then
- read their JSON and be appended to our NPC list.
+ read their JSON and be appended to our NPC array.
\note \l{Container Classes}{Associate containers} can be written by storing
the key in each value object (if it's not already). With this approach, the
@@ -120,10 +120,10 @@
\snippet json/savegame/game.cpp 1
The first thing we do in the read() function is tell the player to read
- itself. We then clear the levels list so that calling loadGame() on the same
- Game object twice doesn't result in old levels hanging around.
+ itself. We then clear the level array so that calling loadGame() on the
+ same Game object twice doesn't result in old levels hanging around.
- We then populate the level list by reading each Level from a QJsonArray.
+ We then populate the level array by reading each Level from a QJsonArray.
\snippet json/savegame/game.cpp 2
@@ -159,20 +159,23 @@
Since we're only interested in demonstrating \e serialization of a game with
JSON, our game is not actually playable. Therefore, we only need
- QCoreApplication and have no event loop. We create our game and assume that
- the player had a great time and made lots of progress, altering the internal
- state of our Character, Level and Game objects.
+ QCoreApplication and have no event loop. On application start-up we parse
+ the command-line arguments to decide how to start the game. For the first
+ argument the options "new" (default) and "load" are available. When "new"
+ is specified a new game will be generated, and when "load" is specified a
+ previously saved game will be loaded in. For the second argument
+ "json" (default) and "binary" are available as options. This argument will
+ decide which file is saved to and/or loaded from. We then move ahead and
+ assume that the player had a great time and made lots of progress, altering
+ the internal state of our Character, Level and Game objects.
\snippet json/savegame/main.cpp 1
When the player has finished, we save their game. For demonstration
- purposes, we serialize to both JSON and binary. You can examine the contents
- of the files in the same directory as the executable, although the binary
- save file will contain some garbage characters (which is normal).
-
- To show that the saved files can be loaded again, we call loadGame() for
- each format, returning \c 1 on failure. Assuming everything went well, we
- return \c 0 to indicate success.
+ purposes, we can serialize to either JSON or binary. You can examine the
+ contents of the files in the same directory as the executable (or re-run
+ the example, making sure to also specify the "load" option), although the
+ binary save file will contain some garbage characters (which is normal).
That concludes our example. As you can see, serialization with Qt's JSON
classes is very simple and convenient. The advantages of using QJsonDocument
diff --git a/examples/corelib/json/savegame/game.cpp b/examples/corelib/json/savegame/game.cpp
index b0d800f4ab..4caec71a03 100644
--- a/examples/corelib/json/savegame/game.cpp
+++ b/examples/corelib/json/savegame/game.cpp
@@ -53,41 +53,54 @@
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
+#include <QRandomGenerator>
+#include <QTextStream>
-Game::Game()
-{
-}
-
-const Character &Game::player() const
+Character Game::player() const
{
return mPlayer;
}
-const QList<Level> &Game::levels() const {
+QVector<Level> Game::levels() const
+{
return mLevels;
}
//! [0]
-void Game::newGame() {
+void Game::newGame()
+{
mPlayer = Character();
mPlayer.setName(QStringLiteral("Hero"));
mPlayer.setClassType(Character::Archer);
- mPlayer.setLevel(15);
+ mPlayer.setLevel(QRandomGenerator::global()->bounded(15, 21));
mLevels.clear();
-
- Level village;
- QList<Character> villageNpcs;
- villageNpcs.append(Character(QStringLiteral("Barry the Blacksmith"), 10, Character::Warrior));
- villageNpcs.append(Character(QStringLiteral("Terry the Trader"), 10, Character::Warrior));
+ mLevels.reserve(2);
+
+ Level village(QStringLiteral("Village"));
+ QVector<Character> villageNpcs;
+ villageNpcs.reserve(2);
+ villageNpcs.append(Character(QStringLiteral("Barry the Blacksmith"),
+ QRandomGenerator::global()->bounded(8, 11),
+ Character::Warrior));
+ villageNpcs.append(Character(QStringLiteral("Terry the Trader"),
+ QRandomGenerator::global()->bounded(6, 8),
+ Character::Warrior));
village.setNpcs(villageNpcs);
mLevels.append(village);
- Level dungeon;
- QList<Character> dungeonNpcs;
- dungeonNpcs.append(Character(QStringLiteral("Eric the Evil"), 20, Character::Mage));
- dungeonNpcs.append(Character(QStringLiteral("Eric's Sidekick #1"), 5, Character::Warrior));
- dungeonNpcs.append(Character(QStringLiteral("Eric's Sidekick #2"), 5, Character::Warrior));
+ Level dungeon(QStringLiteral("Dungeon"));
+ QVector<Character> dungeonNpcs;
+ dungeonNpcs.reserve(3);
+ dungeonNpcs.append(Character(QStringLiteral("Eric the Evil"),
+ QRandomGenerator::global()->bounded(18, 26),
+ Character::Mage));
+ dungeonNpcs.append(Character(QStringLiteral("Eric's Left Minion"),
+ QRandomGenerator::global()->bounded(5, 7),
+ Character::Warrior));
+ dungeonNpcs.append(Character(QStringLiteral("Eric's Right Minion"),
+ QRandomGenerator::global()->bounded(4, 9),
+ Character::Warrior));
dungeon.setNpcs(dungeonNpcs);
mLevels.append(dungeon);
}
@@ -113,6 +126,10 @@ bool Game::loadGame(Game::SaveFormat saveFormat)
read(loadDoc.object());
+ QTextStream(stdout) << "Loaded save for "
+ << loadDoc["player"]["name"].toString()
+ << " using "
+ << (saveFormat != Json ? "binary " : "") << "JSON...\n";
return true;
}
//! [3]
@@ -143,15 +160,19 @@ bool Game::saveGame(Game::SaveFormat saveFormat) const
//! [1]
void Game::read(const QJsonObject &json)
{
- mPlayer.read(json["player"].toObject());
-
- mLevels.clear();
- QJsonArray levelArray = json["levels"].toArray();
- for (int levelIndex = 0; levelIndex < levelArray.size(); ++levelIndex) {
- QJsonObject levelObject = levelArray[levelIndex].toObject();
- Level level;
- level.read(levelObject);
- mLevels.append(level);
+ if (json.contains("player") && json["player"].isObject())
+ mPlayer.read(json["player"].toObject());
+
+ if (json.contains("levels") && json["levels"].isArray()) {
+ QJsonArray levelArray = json["levels"].toArray();
+ mLevels.clear();
+ mLevels.reserve(levelArray.size());
+ for (int levelIndex = 0; levelIndex < levelArray.size(); ++levelIndex) {
+ QJsonObject levelObject = levelArray[levelIndex].toObject();
+ Level level;
+ level.read(levelObject);
+ mLevels.append(level);
+ }
}
}
//! [1]
@@ -172,3 +193,14 @@ void Game::write(QJsonObject &json) const
json["levels"] = levelArray;
}
//! [2]
+
+void Game::print(int indentation) const
+{
+ const QString indent(indentation * 2, ' ');
+ QTextStream(stdout) << indent << "Player\n";
+ mPlayer.print(indentation + 1);
+
+ QTextStream(stdout) << indent << "Levels\n";
+ for (Level level : mLevels)
+ level.print(indentation + 1);
+}
diff --git a/examples/corelib/json/savegame/game.h b/examples/corelib/json/savegame/game.h
index c02832b0ab..3da9c148be 100644
--- a/examples/corelib/json/savegame/game.h
+++ b/examples/corelib/json/savegame/game.h
@@ -52,7 +52,7 @@
#define GAME_H
#include <QJsonObject>
-#include <QList>
+#include <QVector>
#include "character.h"
#include "level.h"
@@ -61,14 +61,12 @@
class Game
{
public:
- Game();
-
enum SaveFormat {
Json, Binary
};
- const Character &player() const;
- const QList<Level> &levels() const;
+ Character player() const;
+ QVector<Level> levels() const;
void newGame();
bool loadGame(SaveFormat saveFormat);
@@ -76,9 +74,11 @@ public:
void read(const QJsonObject &json);
void write(QJsonObject &json) const;
+
+ void print(int indentation = 0) const;
private:
Character mPlayer;
- QList<Level> mLevels;
+ QVector<Level> mLevels;
};
//! [0]
diff --git a/examples/corelib/json/savegame/level.cpp b/examples/corelib/json/savegame/level.cpp
index 5b9fb5c90a..8eda107f46 100644
--- a/examples/corelib/json/savegame/level.cpp
+++ b/examples/corelib/json/savegame/level.cpp
@@ -51,16 +51,23 @@
#include "level.h"
#include <QJsonArray>
+#include <QTextStream>
-Level::Level() {
+Level::Level(const QString &name) : mName(name)
+{
}
-const QList<Character> &Level::npcs() const
+QString Level::name() const
+{
+ return mName;
+}
+
+QVector<Character> Level::npcs() const
{
return mNpcs;
}
-void Level::setNpcs(const QList<Character> &npcs)
+void Level::setNpcs(const QVector<Character> &npcs)
{
mNpcs = npcs;
}
@@ -68,13 +75,19 @@ void Level::setNpcs(const QList<Character> &npcs)
//! [0]
void Level::read(const QJsonObject &json)
{
- mNpcs.clear();
- QJsonArray npcArray = json["npcs"].toArray();
- for (int npcIndex = 0; npcIndex < npcArray.size(); ++npcIndex) {
- QJsonObject npcObject = npcArray[npcIndex].toObject();
- Character npc;
- npc.read(npcObject);
- mNpcs.append(npc);
+ if (json.contains("name") && json["name"].isString())
+ mName = json["name"].toString();
+
+ if (json.contains("npcs") && json["npcs"].isArray()) {
+ QJsonArray npcArray = json["npcs"].toArray();
+ mNpcs.clear();
+ mNpcs.reserve(npcArray.size());
+ for (int npcIndex = 0; npcIndex < npcArray.size(); ++npcIndex) {
+ QJsonObject npcObject = npcArray[npcIndex].toObject();
+ Character npc;
+ npc.read(npcObject);
+ mNpcs.append(npc);
+ }
}
}
//! [0]
@@ -82,6 +95,7 @@ void Level::read(const QJsonObject &json)
//! [1]
void Level::write(QJsonObject &json) const
{
+ json["name"] = mName;
QJsonArray npcArray;
foreach (const Character npc, mNpcs) {
QJsonObject npcObject;
@@ -91,3 +105,13 @@ void Level::write(QJsonObject &json) const
json["npcs"] = npcArray;
}
//! [1]
+
+void Level::print(int indentation) const
+{
+ const QString indent(indentation * 2, ' ');
+ QTextStream(stdout) << indent << "Name:\t" << mName << "\n";
+
+ QTextStream(stdout) << indent << "NPCs:\n";
+ for (const Character &character : mNpcs)
+ character.print(2);
+}
diff --git a/examples/corelib/json/savegame/level.h b/examples/corelib/json/savegame/level.h
index 878510e9d5..393524abfd 100644
--- a/examples/corelib/json/savegame/level.h
+++ b/examples/corelib/json/savegame/level.h
@@ -52,7 +52,7 @@
#define LEVEL_H
#include <QJsonObject>
-#include <QList>
+#include <QVector>
#include "character.h"
@@ -60,15 +60,21 @@
class Level
{
public:
- Level();
+ Level() = default;
+ Level(const QString &name);
- const QList<Character> &npcs() const;
- void setNpcs(const QList<Character> &npcs);
+ QString name() const;
+
+ QVector<Character> npcs() const;
+ void setNpcs(const QVector<Character> &npcs);
void read(const QJsonObject &json);
void write(QJsonObject &json) const;
+
+ void print(int indentation = 0) const;
private:
- QList<Character> mNpcs;
+ QString mName;
+ QVector<Character> mNpcs;
};
//! [0]
diff --git a/examples/corelib/json/savegame/main.cpp b/examples/corelib/json/savegame/main.cpp
index 2e4e864942..d091684211 100644
--- a/examples/corelib/json/savegame/main.cpp
+++ b/examples/corelib/json/savegame/main.cpp
@@ -49,30 +49,32 @@
****************************************************************************/
#include <QCoreApplication>
+#include <QTextStream>
#include "game.h"
//! [0]
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
+ QStringList args = QCoreApplication::arguments();
+ bool newGame = true;
+ if (args.length() > 1)
+ newGame = (args[1].toLower() != QStringLiteral("load"));
+ bool json = true;
+ if (args.length() > 2)
+ json = (args[2].toLower() != QStringLiteral("binary"));
Game game;
- game.newGame();
+ if (newGame)
+ game.newGame();
+ else if (!game.loadGame(json ? Game::Json : Game::Binary))
+ return 1;
// Game is played; changes are made...
//! [0]
//! [1]
- if (!game.saveGame(Game::Json))
- return 1;
-
- if (!game.saveGame(Game::Binary))
- return 1;
-
- Game fromJsonGame;
- if (!fromJsonGame.loadGame(Game::Json))
- return 1;
-
- Game fromBinaryGame;
- if (!fromBinaryGame.loadGame(Game::Binary))
+ QTextStream(stdout) << "Game ended in the following state:\n";
+ game.print();
+ if (!game.saveGame(json ? Game::Json : Game::Binary))
return 1;
return 0;
diff --git a/examples/corelib/threads/queuedcustomtype/main.cpp b/examples/corelib/threads/queuedcustomtype/main.cpp
index 7084b7538a..1f25fafa1b 100644
--- a/examples/corelib/threads/queuedcustomtype/main.cpp
+++ b/examples/corelib/threads/queuedcustomtype/main.cpp
@@ -126,7 +126,6 @@ int main(int argc, char *argv[])
//! [main start] //! [register meta-type for queued communications]
qRegisterMetaType<Block>();
//! [register meta-type for queued communications]
- qsrand(QTime::currentTime().elapsed());
Window window;
window.show();
diff --git a/examples/corelib/threads/queuedcustomtype/renderthread.cpp b/examples/corelib/threads/queuedcustomtype/renderthread.cpp
index f894dd587f..67cedf1e74 100644
--- a/examples/corelib/threads/queuedcustomtype/renderthread.cpp
+++ b/examples/corelib/threads/queuedcustomtype/renderthread.cpp
@@ -50,6 +50,8 @@
#include "renderthread.h"
+#include <QRandomGenerator>
+
RenderThread::RenderThread(QObject *parent)
: QThread(parent)
{
@@ -82,9 +84,9 @@ void RenderThread::run()
for (int s = size; s > 0; --s) {
for (int c = 0; c < 400; ++c) {
//![processing the image (start)]
- int x1 = qMax(0, (qrand() % m_image.width()) - s/2);
+ int x1 = qMax(0, QRandomGenerator::global()->bounded(m_image.width()) - s/2);
int x2 = qMin(x1 + s/2 + 1, m_image.width());
- int y1 = qMax(0, (qrand() % m_image.height()) - s/2);
+ int y1 = qMax(0, QRandomGenerator::global()->bounded(m_image.height()) - s/2);
int y2 = qMin(y1 + s/2 + 1, m_image.height());
int n = 0;
int red = 0;
diff --git a/examples/corelib/threads/semaphores/semaphores.cpp b/examples/corelib/threads/semaphores/semaphores.cpp
index 37dd4cda20..145624bb0b 100644
--- a/examples/corelib/threads/semaphores/semaphores.cpp
+++ b/examples/corelib/threads/semaphores/semaphores.cpp
@@ -70,10 +70,9 @@ class Producer : public QThread
public:
void run() override
{
- qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
for (int i = 0; i < DataSize; ++i) {
freeBytes.acquire();
- buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];
+ buffer[i % BufferSize] = "ACGT"[QRandomGenerator::global()->bounded(4)];
usedBytes.release();
}
}
diff --git a/examples/corelib/threads/waitconditions/waitconditions.cpp b/examples/corelib/threads/waitconditions/waitconditions.cpp
index 9eab28f94c..963ee03a76 100644
--- a/examples/corelib/threads/waitconditions/waitconditions.cpp
+++ b/examples/corelib/threads/waitconditions/waitconditions.cpp
@@ -76,15 +76,13 @@ public:
void run() override
{
- qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
-
for (int i = 0; i < DataSize; ++i) {
mutex.lock();
if (numUsedBytes == BufferSize)
bufferNotFull.wait(&mutex);
mutex.unlock();
- buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];
+ buffer[i % BufferSize] = "ACGT"[QRandomGenerator::global()->bounded(4)];
mutex.lock();
++numUsedBytes;
diff --git a/examples/corelib/tools/contiguouscache/randomlistmodel.cpp b/examples/corelib/tools/contiguouscache/randomlistmodel.cpp
index f3d8f4b133..ccaa45a28b 100644
--- a/examples/corelib/tools/contiguouscache/randomlistmodel.cpp
+++ b/examples/corelib/tools/contiguouscache/randomlistmodel.cpp
@@ -48,6 +48,7 @@
**
****************************************************************************/
#include "randomlistmodel.h"
+#include <QRandomGenerator>
#include <stdlib.h>
static const int bufferSize(500);
@@ -101,6 +102,6 @@ void RandomListModel::cacheRows(int from, int to) const
//![1]
QString RandomListModel::fetchRow(int position) const
{
- return QString::number(rand() % ++position);
+ return QString::number(QRandomGenerator::global()->bounded(++position));
}
//![1]