diff options
author | Liang Qi <liang.qi@qt.io> | 2017-11-21 14:34:31 +0100 |
---|---|---|
committer | Liang Qi <liang.qi@qt.io> | 2017-11-23 09:36:03 +0100 |
commit | 153e8b49adfe210cb00490284a14c94c08e03c3f (patch) | |
tree | 59d9522d6dc96215cc2cb1d19b3e8a0e580bcb41 /examples | |
parent | ef7c0594bf9e41813c9c841e00c3a52269d363f5 (diff) | |
parent | a4113d0c644edba1c39d9d268a259e95ae51c61e (diff) |
Merge remote-tracking branch 'origin/5.10' into dev
Conflicts:
src/network/access/qhttp2protocolhandler_p.h
src/network/kernel/kernel.pri
src/network/ssl/qsslkey_qt.cpp
src/plugins/platforms/cocoa/qcocoascreen.mm
src/plugins/platforms/windows/accessible/iaccessible2.cpp
src/plugins/platforms/windows/accessible/iaccessible2.h
src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp
src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.cpp
src/plugins/platforms/windows/accessible/qwindowsmsaaaccessible.h
src/widgets/widgets/qmenu_p.h
tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
tests/auto/other/qaccessibility/tst_qaccessibility.cpp
tests/auto/testlib/selftests/expected_cmptest.lightxml
tests/auto/testlib/selftests/expected_cmptest.teamcity
tests/auto/testlib/selftests/expected_cmptest.txt
tests/auto/testlib/selftests/expected_cmptest.xml
Done-with: Edward Welbourne <edward.welbourne@qt.io>
Change-Id: I4217cc7d840cbae3e3dd28574741544469c4c6b9
Diffstat (limited to 'examples')
55 files changed, 183 insertions, 179 deletions
diff --git a/examples/corelib/ipc/localfortuneserver/server.cpp b/examples/corelib/ipc/localfortuneserver/server.cpp index 9b8b08bd17..be8d4750d6 100644 --- a/examples/corelib/ipc/localfortuneserver/server.cpp +++ b/examples/corelib/ipc/localfortuneserver/server.cpp @@ -106,7 +106,7 @@ void Server::sendFortune() QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_5_10); - const int fortuneIndex = QRandomGenerator::bounded(0, fortunes.size()); + const int fortuneIndex = QRandomGenerator::global()->bounded(0, fortunes.size()); const QString &message = fortunes.at(fortuneIndex); out << quint32(message.size()); out << message; diff --git a/examples/corelib/json/savegame/game.cpp b/examples/corelib/json/savegame/game.cpp index c70a50121c..4caec71a03 100644 --- a/examples/corelib/json/savegame/game.cpp +++ b/examples/corelib/json/savegame/game.cpp @@ -72,7 +72,7 @@ void Game::newGame() mPlayer = Character(); mPlayer.setName(QStringLiteral("Hero")); mPlayer.setClassType(Character::Archer); - mPlayer.setLevel(QRandomGenerator::bounded(15, 21)); + mPlayer.setLevel(QRandomGenerator::global()->bounded(15, 21)); mLevels.clear(); mLevels.reserve(2); @@ -81,10 +81,10 @@ void Game::newGame() QVector<Character> villageNpcs; villageNpcs.reserve(2); villageNpcs.append(Character(QStringLiteral("Barry the Blacksmith"), - QRandomGenerator::bounded(8, 11), + QRandomGenerator::global()->bounded(8, 11), Character::Warrior)); villageNpcs.append(Character(QStringLiteral("Terry the Trader"), - QRandomGenerator::bounded(6, 8), + QRandomGenerator::global()->bounded(6, 8), Character::Warrior)); village.setNpcs(villageNpcs); mLevels.append(village); @@ -93,13 +93,13 @@ void Game::newGame() QVector<Character> dungeonNpcs; dungeonNpcs.reserve(3); dungeonNpcs.append(Character(QStringLiteral("Eric the Evil"), - QRandomGenerator::bounded(18, 26), + QRandomGenerator::global()->bounded(18, 26), Character::Mage)); dungeonNpcs.append(Character(QStringLiteral("Eric's Left Minion"), - QRandomGenerator::bounded(5, 7), + QRandomGenerator::global()->bounded(5, 7), Character::Warrior)); dungeonNpcs.append(Character(QStringLiteral("Eric's Right Minion"), - QRandomGenerator::bounded(4, 9), + QRandomGenerator::global()->bounded(4, 9), Character::Warrior)); dungeon.setNpcs(dungeonNpcs); mLevels.append(dungeon); 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] diff --git a/examples/embedded/flickable/main.cpp b/examples/embedded/flickable/main.cpp index 9772ba4f55..9367c8b4fe 100644 --- a/examples/embedded/flickable/main.cpp +++ b/examples/embedded/flickable/main.cpp @@ -72,7 +72,7 @@ static QStringList colorPairs(int max) // randomize it colors.clear(); while (combinedColors.count()) { - int i = qrand() % combinedColors.count(); + int i = QRandomGenerator::global()->bounded(combinedColors.count()); colors << combinedColors[i]; combinedColors.removeAt(i); if (colors.count() == max) diff --git a/examples/network/fortuneserver/server.cpp b/examples/network/fortuneserver/server.cpp index 3915a73bf0..7db81fe07a 100644 --- a/examples/network/fortuneserver/server.cpp +++ b/examples/network/fortuneserver/server.cpp @@ -182,7 +182,7 @@ void Server::sendFortune() QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_5_10); - out << fortunes[QRandomGenerator::bounded(fortunes.size())]; + out << fortunes[QRandomGenerator::global()->bounded(fortunes.size())]; //! [4] //! [7] QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); diff --git a/examples/network/threadedfortuneserver/fortuneserver.cpp b/examples/network/threadedfortuneserver/fortuneserver.cpp index 01b77e2aba..791ffc71f4 100644 --- a/examples/network/threadedfortuneserver/fortuneserver.cpp +++ b/examples/network/threadedfortuneserver/fortuneserver.cpp @@ -51,6 +51,8 @@ #include "fortuneserver.h" #include "fortunethread.h" +#include <QRandomGenerator> + #include <stdlib.h> //! [0] @@ -70,7 +72,7 @@ FortuneServer::FortuneServer(QObject *parent) //! [1] void FortuneServer::incomingConnection(qintptr socketDescriptor) { - QString fortune = fortunes.at(qrand() % fortunes.size()); + QString fortune = fortunes.at(QRandomGenerator::global()->bounded(fortunes.size())); FortuneThread *thread = new FortuneThread(socketDescriptor, fortune, this); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); diff --git a/examples/network/threadedfortuneserver/main.cpp b/examples/network/threadedfortuneserver/main.cpp index 3a54585fbc..fdacb28945 100644 --- a/examples/network/threadedfortuneserver/main.cpp +++ b/examples/network/threadedfortuneserver/main.cpp @@ -60,6 +60,5 @@ int main(int argc, char *argv[]) QApplication app(argc, argv); Dialog dialog; dialog.show(); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); return app.exec(); } diff --git a/examples/network/torrent/main.cpp b/examples/network/torrent/main.cpp index de7516ed3f..6430d2e5f3 100644 --- a/examples/network/torrent/main.cpp +++ b/examples/network/torrent/main.cpp @@ -55,7 +55,6 @@ int main(int argc, char *argv[]) { QApplication app(argc, argv); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); Q_INIT_RESOURCE(icons); diff --git a/examples/network/torrent/torrentclient.cpp b/examples/network/torrent/torrentclient.cpp index ba87924ff9..95232646ab 100644 --- a/examples/network/torrent/torrentclient.cpp +++ b/examples/network/torrent/torrentclient.cpp @@ -692,7 +692,7 @@ void TorrentClient::connectToPeers() // Start as many connections as we can while (!weighedPeers.isEmpty() && ConnectionManager::instance()->canAddConnection() - && (qrand() % (ConnectionManager::instance()->maxConnections() / 2))) { + && (QRandomGenerator::global()->bounded(ConnectionManager::instance()->maxConnections() / 2))) { PeerWireClient *client = new PeerWireClient(ConnectionManager::instance()->clientId(), this); RateController::instance()->addSocket(client); ConnectionManager::instance()->addConnection(client); @@ -701,7 +701,7 @@ void TorrentClient::connectToPeers() d->connections << client; // Pick a random peer from the list of weighed peers. - TorrentPeer *peer = weighedPeers.takeAt(qrand() % weighedPeers.size()); + TorrentPeer *peer = weighedPeers.takeAt(QRandomGenerator::global()->bounded(weighedPeers.size())); weighedPeers.removeAll(peer); peer->connectStart = QDateTime::currentSecsSinceEpoch(); peer->lastVisited = peer->connectStart; @@ -1114,7 +1114,7 @@ void TorrentClient::scheduleUploads() } if ((client->peerWireState() & PeerWireClient::ChokingPeer) == 0) { - if ((qrand() % 10) == 0) + if ((QRandomGenerator::global()->bounded(10)) == 0) client->abort(); else client->chokePeer(); @@ -1128,7 +1128,7 @@ void TorrentClient::scheduleUploads() // random peer to allow it to compete for a position among the // downloaders. (This is known as an "optimistic unchoke".) if (!allClients.isEmpty()) { - PeerWireClient *client = allClients[qrand() % allClients.size()]; + PeerWireClient *client = allClients[QRandomGenerator::global()->bounded(allClients.size())]; if (client->peerWireState() & PeerWireClient::ChokingPeer) client->unchokePeer(); } @@ -1189,7 +1189,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client) piece = d->payloads.value(client); if (!piece) { QList<TorrentPiece *> values = d->pendingPieces.values(); - piece = values.value(qrand() % values.size()); + piece = values.value(QRandomGenerator::global()->bounded(values.size())); piece->inProgress = true; d->payloads.insert(client, piece); } @@ -1246,14 +1246,14 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client) ++it; } if (!partialPieces.isEmpty()) - piece = partialPieces.value(qrand() % partialPieces.size()); + piece = partialPieces.value(QRandomGenerator::global()->bounded(partialPieces.size())); if (!piece) { // Pick a random piece 3 out of 4 times; otherwise, pick either // one of the most common or the least common pieces available, // depending on the state we're in. int pieceIndex = 0; - if (d->state == WarmingUp || (qrand() & 4) == 0) { + if (d->state == WarmingUp || (QRandomGenerator::global()->generate() & 4) == 0) { int *occurrences = new int[d->pieceCount]; memset(occurrences, 0, d->pieceCount * sizeof(int)); @@ -1293,7 +1293,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client) } // Select one piece randomly - pieceIndex = piecesReadyForDownload.at(qrand() % piecesReadyForDownload.size()); + pieceIndex = piecesReadyForDownload.at(QRandomGenerator::global()->bounded(piecesReadyForDownload.size())); delete [] occurrences; } else { // Make up a list of available piece indices, and pick @@ -1304,7 +1304,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client) if (incompletePiecesAvailableToClient.testBit(i)) values << i; } - pieceIndex = values.at(qrand() % values.size()); + pieceIndex = values.at(QRandomGenerator::global()->bounded(values.size())); } // Create a new TorrentPiece and fill in all initial @@ -1396,8 +1396,8 @@ int TorrentClient::requestBlocks(PeerWireClient *client, TorrentPiece *piece, in // speedup comes from an increased chance of receiving // different blocks from the different peers. for (int i = 0; i < bits.size(); ++i) { - int a = qrand() % bits.size(); - int b = qrand() % bits.size(); + int a = QRandomGenerator::global()->bounded(bits.size()); + int b = QRandomGenerator::global()->bounded(bits.size()); int tmp = bits[a]; bits[a] = bits[b]; bits[b] = tmp; diff --git a/examples/opengl/hellowindow/hellowindow.cpp b/examples/opengl/hellowindow/hellowindow.cpp index 048190d766..a978e19b79 100644 --- a/examples/opengl/hellowindow/hellowindow.cpp +++ b/examples/opengl/hellowindow/hellowindow.cpp @@ -52,6 +52,7 @@ #include <QOpenGLContext> #include <QOpenGLFunctions> +#include <QRandomGenerator> #include <qmath.h> Renderer::Renderer(const QSurfaceFormat &format, Renderer *share, QScreen *screen) @@ -68,9 +69,9 @@ Renderer::Renderer(const QSurfaceFormat &format, Renderer *share, QScreen *scree m_context->create(); m_backgroundColor = QColor::fromRgbF(0.1f, 0.1f, 0.2f, 1.0f); - m_backgroundColor.setRed(qrand() % 64); - m_backgroundColor.setGreen(qrand() % 128); - m_backgroundColor.setBlue(qrand() % 256); + m_backgroundColor.setRed(QRandomGenerator::global()->bounded(64)); + m_backgroundColor.setGreen(QRandomGenerator::global()->bounded(128)); + m_backgroundColor.setBlue(QRandomGenerator::global()->bounded(256)); } HelloWindow::HelloWindow(const QSharedPointer<Renderer> &renderer, QScreen *screen) diff --git a/examples/opengl/legacy/overpainting/bubble.cpp b/examples/opengl/legacy/overpainting/bubble.cpp index afc50117d0..352e359cf9 100644 --- a/examples/opengl/legacy/overpainting/bubble.cpp +++ b/examples/opengl/legacy/overpainting/bubble.cpp @@ -50,6 +50,8 @@ #include "bubble.h" +#include <QRandomGenerator> + Bubble::Bubble(const QPointF &position, qreal radius, const QPointF &velocity) : position(position), vel(velocity), radius(radius) { @@ -80,10 +82,10 @@ void Bubble::drawBubble(QPainter *painter) QColor Bubble::randomColor() { - int red = int(205 + 50.0*qrand()/(RAND_MAX+1.0)); - int green = int(205 + 50.0*qrand()/(RAND_MAX+1.0)); - int blue = int(205 + 50.0*qrand()/(RAND_MAX+1.0)); - int alpha = int(91 + 100.0*qrand()/(RAND_MAX+1.0)); + int red = int(205 + QRandomGenerator::global()->bounded(50)); + int green = int(205 + QRandomGenerator::global()->bounded(50)); + int blue = int(205 + QRandomGenerator::global()->bounded(50)); + int alpha = int(91 + QRandomGenerator::global()->bounded(100)); return QColor(red, green, blue, alpha); } diff --git a/examples/opengl/legacy/overpainting/glwidget.cpp b/examples/opengl/legacy/overpainting/glwidget.cpp index 7e9f4a5beb..1ec7bd731c 100644 --- a/examples/opengl/legacy/overpainting/glwidget.cpp +++ b/examples/opengl/legacy/overpainting/glwidget.cpp @@ -53,6 +53,7 @@ #include "glwidget.h" #include <QMouseEvent> +#include <QRandomGenerator> #include <QTime> #include <math.h> @@ -67,7 +68,6 @@ GLWidget::GLWidget(QWidget *parent) : QGLWidget(QGLFormat(QGL::SampleBuffers), parent) { QTime midnight(0, 0, 0); - qsrand(midnight.secsTo(QTime::currentTime())); logo = 0; xRot = 0; @@ -234,11 +234,11 @@ QSize GLWidget::sizeHint() const void GLWidget::createBubbles(int number) { for (int i = 0; i < number; ++i) { - QPointF position(width()*(0.1 + (0.8*qrand()/(RAND_MAX+1.0))), - height()*(0.1 + (0.8*qrand()/(RAND_MAX+1.0)))); - qreal radius = qMin(width(), height())*(0.0125 + 0.0875*qrand()/(RAND_MAX+1.0)); - QPointF velocity(width()*0.0125*(-0.5 + qrand()/(RAND_MAX+1.0)), - height()*0.0125*(-0.5 + qrand()/(RAND_MAX+1.0))); + QPointF position(width()*(0.1 + QRandomGenerator::global()->bounded(0.8)), + height()*(0.1 + QRandomGenerator::global()->bounded(0.8))); + qreal radius = qMin(width(), height())*(0.0125 + QRandomGenerator::global()->bounded(0.0875)); + QPointF velocity(width()*0.0125*(-0.5 + QRandomGenerator::global()->bounded(1.0)), + height()*0.0125*(-0.5 + QRandomGenerator::global()->bounded(1.0))); bubbles.append(new Bubble(position, radius, velocity)); } diff --git a/examples/opengl/qopenglwidget/bubble.cpp b/examples/opengl/qopenglwidget/bubble.cpp index adf5742f6a..dbaf460f6f 100644 --- a/examples/opengl/qopenglwidget/bubble.cpp +++ b/examples/opengl/qopenglwidget/bubble.cpp @@ -109,10 +109,10 @@ void Bubble::drawBubble(QPainter *painter) QColor Bubble::randomColor() { - int red = int(185 + 70.0*qrand()/(RAND_MAX+1.0)); - int green = int(185 + 70.0*qrand()/(RAND_MAX+1.0)); - int blue = int(205 + 50.0*qrand()/(RAND_MAX+1.0)); - int alpha = int(91 + 100.0*qrand()/(RAND_MAX+1.0)); + int red = int(185 + QRandomGenerator::global()->bounded(70)); + int green = int(185 + QRandomGenerator::global()->bounded(70)); + int blue = int(205 + QRandomGenerator::global()->bounded(50)); + int alpha = int(91 + QRandomGenerator::global()->bounded(100)); return QColor(red, green, blue, alpha); } diff --git a/examples/opengl/qopenglwidget/glwidget.cpp b/examples/opengl/qopenglwidget/glwidget.cpp index 40a1258dd5..3fe919f94b 100644 --- a/examples/opengl/qopenglwidget/glwidget.cpp +++ b/examples/opengl/qopenglwidget/glwidget.cpp @@ -53,6 +53,7 @@ #include <QPaintEngine> #include <QOpenGLShaderProgram> #include <QOpenGLTexture> +#include <QRandomGenerator> #include <QCoreApplication> #include <qmath.h> @@ -420,11 +421,11 @@ void GLWidget::paintGL() void GLWidget::createBubbles(int number) { for (int i = 0; i < number; ++i) { - QPointF position(width()*(0.1 + (0.8*qrand()/(RAND_MAX+1.0))), - height()*(0.1 + (0.8*qrand()/(RAND_MAX+1.0)))); - qreal radius = qMin(width(), height())*(0.0175 + 0.0875*qrand()/(RAND_MAX+1.0)); - QPointF velocity(width()*0.0175*(-0.5 + qrand()/(RAND_MAX+1.0)), - height()*0.0175*(-0.5 + qrand()/(RAND_MAX+1.0))); + QPointF position(width()*(0.1 + QRandomGenerator::global()->bounded(0.8)), + height()*(0.1 + QRandomGenerator::global()->bounded(0.8))); + qreal radius = qMin(width(), height())*(0.0175 + QRandomGenerator::global()->bounded(0.0875)); + QPointF velocity(width()*0.0175*(-0.5 + QRandomGenerator::global()->bounded(1.0)), + height()*0.0175*(-0.5 + QRandomGenerator::global()->bounded(1.0))); m_bubbles.append(new Bubble(position, radius, velocity)); } diff --git a/examples/opengl/qopenglwidget/mainwindow.cpp b/examples/opengl/qopenglwidget/mainwindow.cpp index 1bb2aa2bf0..4bd123628f 100644 --- a/examples/opengl/qopenglwidget/mainwindow.cpp +++ b/examples/opengl/qopenglwidget/mainwindow.cpp @@ -56,6 +56,7 @@ #include <QSlider> #include <QLabel> #include <QCheckBox> +#include <QRandomGenerator> #include <QSpinBox> #include <QScrollArea> @@ -155,7 +156,9 @@ void MainWindow::addNew() { if (m_nextY == 4) return; - GLWidget *w = new GLWidget(this, false, qRgb(qrand() % 256, qrand() % 256, qrand() % 256)); + GLWidget *w = new GLWidget(this, false, qRgb(QRandomGenerator::global()->bounded(256), + QRandomGenerator::global()->bounded(256), + QRandomGenerator::global()->bounded(256))); m_glWidgets << w; connect(m_timer, &QTimer::timeout, w, QOverload<>::of(&QWidget::update)); m_layout->addWidget(w, m_nextY, m_nextX, 1, 1); diff --git a/examples/qtconcurrent/imagescaling/imagescaling.cpp b/examples/qtconcurrent/imagescaling/imagescaling.cpp index 0a230c1194..6d22bb9598 100644 --- a/examples/qtconcurrent/imagescaling/imagescaling.cpp +++ b/examples/qtconcurrent/imagescaling/imagescaling.cpp @@ -48,15 +48,10 @@ ** ****************************************************************************/ #include "imagescaling.h" -#include <qmath.h> -const int imageSize = 100; +#include <qmath.h> -QImage scale(const QString &imageFileName) -{ - QImage image(imageFileName); - return image.scaled(QSize(imageSize, imageSize), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); -} +#include <functional> Images::Images(QWidget *parent) : QWidget(parent) @@ -65,19 +60,19 @@ Images::Images(QWidget *parent) resize(800, 600); imageScaling = new QFutureWatcher<QImage>(this); - connect(imageScaling, SIGNAL(resultReadyAt(int)), SLOT(showImage(int))); - connect(imageScaling, SIGNAL(finished()), SLOT(finished())); + connect(imageScaling, &QFutureWatcher<QImage>::resultReadyAt, this, &Images::showImage); + connect(imageScaling, &QFutureWatcher<QImage>::finished, this, &Images::finished); openButton = new QPushButton(tr("Open Images")); - connect(openButton, SIGNAL(clicked()), SLOT(open())); + connect(openButton, &QPushButton::clicked, this, &Images::open); cancelButton = new QPushButton(tr("Cancel")); cancelButton->setEnabled(false); - connect(cancelButton, SIGNAL(clicked()), imageScaling, SLOT(cancel())); + connect(cancelButton, &QPushButton::clicked, imageScaling, &QFutureWatcher<QImage>::cancel); pauseButton = new QPushButton(tr("Pause/Resume")); pauseButton->setEnabled(false); - connect(pauseButton, SIGNAL(clicked()), imageScaling, SLOT(togglePaused())); + connect(pauseButton, &QPushButton::clicked, imageScaling, &QFutureWatcher<QImage>::togglePaused); QHBoxLayout *buttonLayout = new QHBoxLayout(); buttonLayout->addWidget(openButton); @@ -113,9 +108,11 @@ void Images::open() QStandardPaths::writableLocation(QStandardPaths::PicturesLocation), "*.jpg *.png"); - if (files.count() == 0) + if (files.isEmpty()) return; + const int imageSize = 100; + // Do a simple layout. qDeleteAll(labels); labels.clear(); @@ -130,6 +127,11 @@ void Images::open() } } + std::function<QImage(const QString&)> scale = [imageSize](const QString &imageFileName) { + QImage image(imageFileName); + return image.scaled(QSize(imageSize, imageSize), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + }; + // Use mapped to run the thread safe scale function on the files. imageScaling->setFuture(QtConcurrent::mapped(files, scale)); diff --git a/examples/qtconcurrent/imagescaling/imagescaling.h b/examples/qtconcurrent/imagescaling/imagescaling.h index e2168e4b02..fe9c801387 100644 --- a/examples/qtconcurrent/imagescaling/imagescaling.h +++ b/examples/qtconcurrent/imagescaling/imagescaling.h @@ -57,9 +57,9 @@ class Images : public QWidget { Q_OBJECT public: - Images(QWidget *parent = 0); + Images(QWidget *parent = nullptr); ~Images(); -public Q_SLOTS: +public slots: void open(); void showImage(int num); void finished(); diff --git a/examples/qtconcurrent/map/main.cpp b/examples/qtconcurrent/map/main.cpp index d01b91fe55..8fc670b64b 100644 --- a/examples/qtconcurrent/map/main.cpp +++ b/examples/qtconcurrent/map/main.cpp @@ -55,11 +55,7 @@ #include <QGuiApplication> #include <qtconcurrentmap.h> -QImage scale(const QImage &image) -{ - qDebug() << "Scaling image in thread" << QThread::currentThread(); - return image.scaled(QSize(100, 100), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); -} +#include <functional> int main(int argc, char *argv[]) { @@ -72,6 +68,12 @@ int main(int argc, char *argv[]) for (int i = 0; i < imageCount; ++i) images.append(QImage(1600, 1200, QImage::Format_ARGB32_Premultiplied)); + std::function<QImage(const QImage&)> scale = [](const QImage &image) -> QImage + { + qDebug() << "Scaling image in thread" << QThread::currentThread(); + return image.scaled(QSize(100, 100), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + }; + // Use QtConcurrentBlocking::mapped to apply the scale function to all the // images in the list. QList<QImage> thumbnails = QtConcurrent::blockingMapped(images, scale); diff --git a/examples/qtconcurrent/progressdialog/main.cpp b/examples/qtconcurrent/progressdialog/main.cpp index 0f251c00f1..c277111813 100644 --- a/examples/qtconcurrent/progressdialog/main.cpp +++ b/examples/qtconcurrent/progressdialog/main.cpp @@ -51,24 +51,16 @@ #include <QtWidgets> #include <QtConcurrent> -using namespace QtConcurrent; - -const int iterations = 20; +#include <functional> -void spin(int &iteration) -{ - const int work = 1000 * 1000 * 40; - volatile int v = 0; - for (int j = 0; j < work; ++j) - ++v; - - qDebug() << "iteration" << iteration << "in thread" << QThread::currentThreadId(); -} +using namespace QtConcurrent; int main(int argc, char **argv) { QApplication app(argc, argv); + const int iterations = 20; + // Prepare the vector. QVector<int> vector; for (int i = 0; i < iterations; ++i) @@ -80,10 +72,20 @@ int main(int argc, char **argv) // Create a QFutureWatcher and connect signals and slots. QFutureWatcher<void> futureWatcher; - QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset())); - QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel())); - QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int,int)), &dialog, SLOT(setRange(int,int))); - QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int))); + QObject::connect(&futureWatcher, &QFutureWatcher<void>::finished, &dialog, &QProgressDialog::reset); + QObject::connect(&dialog, &QProgressDialog::canceled, &futureWatcher, &QFutureWatcher<void>::cancel); + QObject::connect(&futureWatcher, &QFutureWatcher<void>::progressRangeChanged, &dialog, &QProgressDialog::setRange); + QObject::connect(&futureWatcher, &QFutureWatcher<void>::progressValueChanged, &dialog, &QProgressDialog::setValue); + + // Our function to compute + std::function<void(int&)> spin = [](int &iteration) { + const int work = 1000 * 1000 * 40; + volatile int v = 0; + for (int j = 0; j < work; ++j) + ++v; + + qDebug() << "iteration" << iteration << "in thread" << QThread::currentThreadId(); + }; // Start the computation. futureWatcher.setFuture(QtConcurrent::map(vector, spin)); diff --git a/examples/qtconcurrent/wordcount/main.cpp b/examples/qtconcurrent/wordcount/main.cpp index a5f8909f34..ff7ea24ee7 100644 --- a/examples/qtconcurrent/wordcount/main.cpp +++ b/examples/qtconcurrent/wordcount/main.cpp @@ -65,15 +65,17 @@ using namespace QtConcurrent; /* Utility function that recursivily searches for files. */ -QStringList findFiles(const QString &startDir, QStringList filters) +QStringList findFiles(const QString &startDir, const QStringList &filters) { QStringList names; QDir dir(startDir); - foreach (QString file, dir.entryList(filters, QDir::Files)) + const auto files = dir.entryList(filters, QDir::Files); + for (const QString &file : files) names += startDir + '/' + file; - foreach (QString subdir, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot)) + const auto subdirs = dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot); + for (const QString &subdir : subdirs) names += findFiles(startDir + '/' + subdir, filters); return names; } @@ -83,17 +85,18 @@ typedef QMap<QString, int> WordCount; /* Single threaded word counter function. */ -WordCount singleThreadedWordCount(QStringList files) +WordCount singleThreadedWordCount(const QStringList &files) { WordCount wordCount; - foreach (QString file, files) { + for (const QString &file : files) { QFile f(file); f.open(QIODevice::ReadOnly); QTextStream textStream(&f); - while (textStream.atEnd() == false) - foreach (const QString &word, textStream.readLine().split(' ')) + while (!textStream.atEnd()) { + const auto words = textStream.readLine().split(' '); + for (const QString &word : words) wordCount[word] += 1; - + } } return wordCount; } @@ -109,9 +112,11 @@ WordCount countWords(const QString &file) QTextStream textStream(&f); WordCount wordCount; - while (textStream.atEnd() == false) - foreach (const QString &word, textStream.readLine().split(' ')) + while (!textStream.atEnd()) { + const auto words = textStream.readLine().split(' '); + for (const QString &word : words) wordCount[word] += 1; + } return wordCount; } @@ -137,8 +142,6 @@ int main(int argc, char** argv) qDebug() << "warmup"; { - QTime time; - time.start(); WordCount total = singleThreadedWordCount(files); } diff --git a/examples/touch/pinchzoom/main.cpp b/examples/touch/pinchzoom/main.cpp index 67099618c7..938432600f 100644 --- a/examples/touch/pinchzoom/main.cpp +++ b/examples/touch/pinchzoom/main.cpp @@ -61,7 +61,6 @@ static const int MouseCount = 7; int main(int argc, char **argv) { QApplication app(argc, argv); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); //! [0] //! [1] diff --git a/examples/touch/pinchzoom/mouse.cpp b/examples/touch/pinchzoom/mouse.cpp index 7f8c238e6f..1e6814be13 100644 --- a/examples/touch/pinchzoom/mouse.cpp +++ b/examples/touch/pinchzoom/mouse.cpp @@ -52,6 +52,7 @@ #include <QGraphicsScene> #include <QPainter> +#include <QRandomGenerator> #include <QStyleOption> #include <qmath.h> @@ -70,9 +71,9 @@ static qreal normalizeAngle(qreal angle) //! [0] Mouse::Mouse() : angle(0), speed(0), mouseEyeDirection(0), - color(qrand() % 256, qrand() % 256, qrand() % 256) + color(QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256)) { - setTransform(QTransform().rotate(qrand() % (360 * 16)), true); + setTransform(QTransform().rotate(QRandomGenerator::global()->bounded(360 * 16)), true); startTimer(1000 / 33); } //! [0] @@ -184,16 +185,16 @@ void Mouse::timerEvent(QTimerEvent *) // Add some random movement //! [10] - if (dangerMice.size() > 1 && (qrand() % 10) == 0) { - if (qrand() % 1) - angle += (qrand() % 100) / 500.0; + if (dangerMice.size() > 1 && QRandomGenerator::global()->bounded(10) == 0) { + if (QRandomGenerator::global()->bounded(1)) + angle += QRandomGenerator::global()->bounded(1 / 500.0); else - angle -= (qrand() % 100) / 500.0; + angle -= QRandomGenerator::global()->bounded(1 / 500.0); } //! [10] //! [11] - speed += (-50 + qrand() % 100) / 100.0; + speed += (-50 + QRandomGenerator::global()->bounded(100)) / 100.0; qreal dx = ::sin(angle) * 10; mouseEyeDirection = (qAbs(dx / 5) < 1) ? 0 : dx / 5; diff --git a/examples/widgets/animation/animatedtiles/main.cpp b/examples/widgets/animation/animatedtiles/main.cpp index 0511fe8162..89b5b67f8a 100644 --- a/examples/widgets/animation/animatedtiles/main.cpp +++ b/examples/widgets/animation/animatedtiles/main.cpp @@ -50,6 +50,7 @@ #include <QtWidgets> #include <QtCore/qmath.h> +#include <QtCore/qrandom.h> #include <QtCore/qstate.h> class Pixmap : public QObject, public QGraphicsPixmapItem @@ -202,8 +203,8 @@ int main(int argc, char **argv) // Random randomState->assignProperty(item, "pos", - QPointF(-250 + qrand() % 500, - -250 + qrand() % 500)); + QPointF(-250 + QRandomGenerator::global()->bounded(500), + -250 + QRandomGenerator::global()->bounded(500))); // Tiled tiledState->assignProperty(item, "pos", diff --git a/examples/widgets/animation/moveblocks/main.cpp b/examples/widgets/animation/moveblocks/main.cpp index a9b95808a5..6d17696108 100644 --- a/examples/widgets/animation/moveblocks/main.cpp +++ b/examples/widgets/animation/moveblocks/main.cpp @@ -125,7 +125,7 @@ public: void onEntry(QEvent *) override { int n; - while ((n = (qrand() % m_stateCount + 1)) == m_lastIndex) + while ((n = QRandomGenerator::global()->bounded(m_stateCount) + 1) == m_lastIndex) { } m_lastIndex = n; machine()->postEvent(new StateSwitchEvent(n)); @@ -323,8 +323,6 @@ int main(int argc, char **argv) window.resize(300, 300); window.show(); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); - return app.exec(); } diff --git a/examples/widgets/animation/stickman/lifecycle.cpp b/examples/widgets/animation/stickman/lifecycle.cpp index 253af22b2d..dbe9a299b4 100644 --- a/examples/widgets/animation/stickman/lifecycle.cpp +++ b/examples/widgets/animation/stickman/lifecycle.cpp @@ -91,13 +91,12 @@ public: : QEventTransition(this, QEvent::Timer) { setTargetState(target); - qsrand((uint)QDateTime::currentSecsSinceEpoch()); startTimer(1000); } bool eventTest(QEvent *e) override { - return QEventTransition::eventTest(e) && ((qrand() % 50) == 0); + return QEventTransition::eventTest(e) && QRandomGenerator::global()->bounded(50) == 0; } }; //! [4] diff --git a/examples/widgets/animation/sub-attaq/main.cpp b/examples/widgets/animation/sub-attaq/main.cpp index f65ca7be18..9b28d8c40f 100644 --- a/examples/widgets/animation/sub-attaq/main.cpp +++ b/examples/widgets/animation/sub-attaq/main.cpp @@ -57,8 +57,6 @@ int main(int argc, char *argv[]) QApplication app(argc, argv); Q_INIT_RESOURCE(subattaq); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); - MainWindow w; w.show(); diff --git a/examples/widgets/animation/sub-attaq/states.cpp b/examples/widgets/animation/sub-attaq/states.cpp index 21cff048e7..e19704db7b 100644 --- a/examples/widgets/animation/sub-attaq/states.cpp +++ b/examples/widgets/animation/sub-attaq/states.cpp @@ -64,6 +64,7 @@ #include <QtCore/QStateMachine> #include <QtWidgets/QKeyEventTransition> #include <QtCore/QFinalState> +#include <QtCore/QRandomGenerator> PlayState::PlayState(GraphicsScene *scene, QState *parent) : QState(parent), @@ -193,12 +194,12 @@ void LevelState::initializeLevel() for (int j = 0; j < subContent.second; ++j ) { SubMarine *sub = new SubMarine(submarineDesc.type, submarineDesc.name, submarineDesc.points); scene->addItem(sub); - int random = (qrand() % 15 + 1); + int random = QRandomGenerator::global()->bounded(15) + 1; qreal x = random == 13 || random == 5 ? 0 : scene->width() - sub->size().width(); - qreal y = scene->height() -(qrand() % 150 + 1) - sub->size().height(); + qreal y = scene->height() -(QRandomGenerator::global()->bounded(150) + 1) - sub->size().height(); sub->setPos(x,y); sub->setCurrentDirection(x == 0 ? SubMarine::Right : SubMarine::Left); - sub->setCurrentSpeed(qrand() % 3 + 1); + sub->setCurrentSpeed(QRandomGenerator::global()->bounded(3) + 1); } } } diff --git a/examples/widgets/animation/sub-attaq/submarine_p.h b/examples/widgets/animation/sub-attaq/submarine_p.h index b8d5532962..698b4b494f 100644 --- a/examples/widgets/animation/sub-attaq/submarine_p.h +++ b/examples/widgets/animation/sub-attaq/submarine_p.h @@ -69,6 +69,7 @@ //Qt #include <QtCore/QPropertyAnimation> +#include <QtCore/QRandomGenerator> #include <QtWidgets/QGraphicsScene> //This state is describing when the boat is moving right @@ -88,8 +89,8 @@ public: protected slots: void onAnimationMovementValueChanged(const QVariant &) { - if (qrand() % 200 + 1 == 3) - submarine->launchTorpedo(qrand() % 3 + 1); + if (QRandomGenerator::global()->bounded(200) + 1 == 3) + submarine->launchTorpedo(QRandomGenerator::global()->bounded(3) + 1); } protected: diff --git a/examples/widgets/doc/src/collidingmice-example.qdoc b/examples/widgets/doc/src/collidingmice-example.qdoc index 02417ba521..535057bb6a 100644 --- a/examples/widgets/doc/src/collidingmice-example.qdoc +++ b/examples/widgets/doc/src/collidingmice-example.qdoc @@ -80,8 +80,7 @@ \snippet graphicsview/collidingmice/mouse.cpp 0 To calculate the various components of the mouse's color, we use - the global qrand() function which is a thread-safe version of the - standard C++ rand() function. + \l QRandomGenerator. Then we call the \l {QGraphicsItem::setRotation()}{setRotation()} function inherited from QGraphicsItem. Items live in their own local @@ -178,12 +177,7 @@ \snippet graphicsview/collidingmice/main.cpp 0 - First, we create an application object and call the global - qsrand() function to specify the seed used to generate a new - random number sequence of pseudo random integers with the - previously mentioned qrand() function. - - Then it is time to create the scene: + First, we create an application object and create the scene: \snippet graphicsview/collidingmice/main.cpp 1 diff --git a/examples/widgets/doc/src/dragdroprobot.qdoc b/examples/widgets/doc/src/dragdroprobot.qdoc index ac221ec5f9..f74b898e1b 100644 --- a/examples/widgets/doc/src/dragdroprobot.qdoc +++ b/examples/widgets/doc/src/dragdroprobot.qdoc @@ -257,7 +257,7 @@ \snippet graphicsview/dragdroprobot/coloritem.cpp 0 \c ColorItem's constructor assigns an opaque random color to its color - member by making use of qrand(). For improved usability, it assigns a + member by making use of \l QRandomGenerator. For improved usability, it assigns a tooltip that provides a useful hint to the user, and it also sets a suitable cursor. This ensures that the cursor will chance to Qt::OpenHandCursor when the mouse pointer hovers over the item. diff --git a/examples/widgets/doc/src/elasticnodes.qdoc b/examples/widgets/doc/src/elasticnodes.qdoc index 09ac891b24..65e1195121 100644 --- a/examples/widgets/doc/src/elasticnodes.qdoc +++ b/examples/widgets/doc/src/elasticnodes.qdoc @@ -424,9 +424,8 @@ \section1 The main() Function In contrast to the complexity of the rest of this example, the \c main() - function is very simple: We create a QApplication instance, seed the - randomizer using qsrand(), and then create and show an instance of \c - GraphWidget. Because all nodes in the grid are moved initially, the \c - GraphWidget timer will start immediately after control has returned to the - event loop. + function is very simple: We create a QApplication instance, then create and + show an instance of \c GraphWidget. Because all nodes in the grid are moved + initially, the \c GraphWidget timer will start immediately after control + has returned to the event loop. */ diff --git a/examples/widgets/draganddrop/puzzle/mainwindow.cpp b/examples/widgets/draganddrop/puzzle/mainwindow.cpp index 1914519c68..98a7cd4265 100644 --- a/examples/widgets/draganddrop/puzzle/mainwindow.cpp +++ b/examples/widgets/draganddrop/puzzle/mainwindow.cpp @@ -122,10 +122,8 @@ void MainWindow::setupPuzzle() } } - qsrand(QCursor::pos().x() ^ QCursor::pos().y()); - for (int i = 0; i < piecesList->count(); ++i) { - if (int(2.0*qrand()/(RAND_MAX+1.0)) == 1) { + if (QRandomGenerator::global()->bounded(2) == 1) { QListWidgetItem *item = piecesList->takeItem(i); piecesList->insertItem(0, item); } diff --git a/examples/widgets/graphicsview/boxes/qtbox.cpp b/examples/widgets/graphicsview/boxes/qtbox.cpp index 9a19985fac..3a184dd0b6 100644 --- a/examples/widgets/graphicsview/boxes/qtbox.cpp +++ b/examples/widgets/graphicsview/boxes/qtbox.cpp @@ -414,7 +414,7 @@ void QtBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWi CircleItem::CircleItem(int size, int x, int y) : ItemBase(size, x, y) { - m_color = QColor::fromHsv(rand() % 360, 255, 255); + m_color = QColor::fromHsv(QRandomGenerator::global()->bounded(360), 255, 255); } void CircleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) diff --git a/examples/widgets/graphicsview/boxes/scene.cpp b/examples/widgets/graphicsview/boxes/scene.cpp index 31b9553c75..f51cad99ac 100644 --- a/examples/widgets/graphicsview/boxes/scene.cpp +++ b/examples/widgets/graphicsview/boxes/scene.cpp @@ -50,6 +50,7 @@ #include <QDebug> #include "scene.h" +#include <QtCore/QRandomGenerator> #include <QtGui/qmatrix4x4.h> #include <QtGui/qvector3d.h> #include <qmath.h> @@ -1072,13 +1073,16 @@ void Scene::newItem(ItemDialog::ItemType type) QSize size = sceneRect().size().toSize(); switch (type) { case ItemDialog::QtBoxItem: - addItem(new QtBox(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); + addItem(new QtBox(64, QRandomGenerator::global()->bounded(size.width() - 64) + 32, + QRandomGenerator::global()->bounded(size.height() - 64) + 32)); break; case ItemDialog::CircleItem: - addItem(new CircleItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); + addItem(new CircleItem(64, QRandomGenerator::global()->bounded(size.width() - 64) + 32, + QRandomGenerator::global()->bounded(size.height() - 64) + 32)); break; case ItemDialog::SquareItem: - addItem(new SquareItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); + addItem(new SquareItem(64, QRandomGenerator::global()->bounded(size.width() - 64) + 32, + QRandomGenerator::global()->bounded(size.height() - 64) + 32)); break; default: break; diff --git a/examples/widgets/graphicsview/collidingmice/main.cpp b/examples/widgets/graphicsview/collidingmice/main.cpp index a0659b9bc1..91aee70b86 100644 --- a/examples/widgets/graphicsview/collidingmice/main.cpp +++ b/examples/widgets/graphicsview/collidingmice/main.cpp @@ -60,7 +60,6 @@ static const int MouseCount = 7; int main(int argc, char **argv) { QApplication app(argc, argv); - qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime())); //! [0] //! [1] diff --git a/examples/widgets/graphicsview/collidingmice/mouse.cpp b/examples/widgets/graphicsview/collidingmice/mouse.cpp index 298e4aae64..14f887f6e3 100644 --- a/examples/widgets/graphicsview/collidingmice/mouse.cpp +++ b/examples/widgets/graphicsview/collidingmice/mouse.cpp @@ -52,6 +52,7 @@ #include <QGraphicsScene> #include <QPainter> +#include <QRandomGenerator> #include <QStyleOption> #include <qmath.h> @@ -70,9 +71,9 @@ static qreal normalizeAngle(qreal angle) //! [0] Mouse::Mouse() : angle(0), speed(0), mouseEyeDirection(0), - color(qrand() % 256, qrand() % 256, qrand() % 256) + color(QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256)) { - setRotation(qrand() % (360 * 16)); + setRotation(QRandomGenerator::global()->bounded(360 * 16)); } //! [0] @@ -185,16 +186,16 @@ void Mouse::advance(int step) // Add some random movement //! [10] - if (dangerMice.size() > 1 && (qrand() % 10) == 0) { - if (qrand() % 1) - angle += (qrand() % 100) / 500.0; + if (dangerMice.size() > 1 && QRandomGenerator::global()->bounded(10) == 0) { + if (QRandomGenerator::global()->bounded(1)) + angle += QRandomGenerator::global()->bounded(1 / 500.0); else - angle -= (qrand() % 100) / 500.0; + angle -= QRandomGenerator::global()->bounded(1 / 500.0); } //! [10] //! [11] - speed += (-50 + qrand() % 100) / 100.0; + speed += (-50 + QRandomGenerator::global()->bounded(100)) / 100.0; qreal dx = ::sin(angle) * 10; mouseEyeDirection = (qAbs(dx / 5) < 1) ? 0 : dx / 5; diff --git a/examples/widgets/graphicsview/dragdroprobot/coloritem.cpp b/examples/widgets/graphicsview/dragdroprobot/coloritem.cpp index 64a715d31f..262e18a317 100644 --- a/examples/widgets/graphicsview/dragdroprobot/coloritem.cpp +++ b/examples/widgets/graphicsview/dragdroprobot/coloritem.cpp @@ -54,7 +54,7 @@ //! [0] ColorItem::ColorItem() - : color(qrand() % 256, qrand() % 256, qrand() % 256) + : color(QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256)) { setToolTip(QString("QColor(%1, %2, %3)\n%4") .arg(color.red()).arg(color.green()).arg(color.blue()) @@ -107,7 +107,7 @@ void ColorItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) //! [6] static int n = 0; - if (n++ > 2 && (qrand() % 3) == 0) { + if (n++ > 2 && QRandomGenerator::global()->bounded(3) == 0) { QImage image(":/images/head.png"); mime->setImageData(image); diff --git a/examples/widgets/graphicsview/dragdroprobot/main.cpp b/examples/widgets/graphicsview/dragdroprobot/main.cpp index 20cec92d26..045e184569 100644 --- a/examples/widgets/graphicsview/dragdroprobot/main.cpp +++ b/examples/widgets/graphicsview/dragdroprobot/main.cpp @@ -73,7 +73,6 @@ int main(int argc, char **argv) { QApplication app(argc, argv); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); //! [0] //! [1] QGraphicsScene scene(-200, -200, 400, 400); diff --git a/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp b/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp index 844c8f8aac..4259aab803 100644 --- a/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp +++ b/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp @@ -55,6 +55,7 @@ #include <math.h> #include <QKeyEvent> +#include <QRandomGenerator> //! [0] GraphWidget::GraphWidget(QWidget *parent) @@ -247,7 +248,7 @@ void GraphWidget::shuffle() { foreach (QGraphicsItem *item, scene()->items()) { if (qgraphicsitem_cast<Node *>(item)) - item->setPos(-150 + qrand() % 300, -150 + qrand() % 300); + item->setPos(-150 + QRandomGenerator::global()->bounded(300), -150 + QRandomGenerator::global()->bounded(300)); } } diff --git a/examples/widgets/graphicsview/elasticnodes/main.cpp b/examples/widgets/graphicsview/elasticnodes/main.cpp index 75cc4b0f69..1e372a9f6d 100644 --- a/examples/widgets/graphicsview/elasticnodes/main.cpp +++ b/examples/widgets/graphicsview/elasticnodes/main.cpp @@ -57,7 +57,6 @@ int main(int argc, char **argv) { QApplication app(argc, argv); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); GraphWidget *widget = new GraphWidget; diff --git a/examples/widgets/itemviews/puzzle/mainwindow.cpp b/examples/widgets/itemviews/puzzle/mainwindow.cpp index 8ee5cf659e..d598dc9017 100644 --- a/examples/widgets/itemviews/puzzle/mainwindow.cpp +++ b/examples/widgets/itemviews/puzzle/mainwindow.cpp @@ -114,8 +114,6 @@ void MainWindow::setupPuzzle() (puzzleImage.height() - size) / 2, size, size).scaled(puzzleWidget->imageSize(), puzzleWidget->imageSize(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); - qsrand(QCursor::pos().x() ^ QCursor::pos().y()); - model->addPieces(puzzleImage); puzzleWidget->clear(); } diff --git a/examples/widgets/itemviews/puzzle/piecesmodel.cpp b/examples/widgets/itemviews/puzzle/piecesmodel.cpp index 0fbf0cdcc2..f0649d3776 100644 --- a/examples/widgets/itemviews/puzzle/piecesmodel.cpp +++ b/examples/widgets/itemviews/puzzle/piecesmodel.cpp @@ -52,6 +52,7 @@ #include <QIcon> #include <QMimeData> +#include <QRandomGenerator> PiecesModel::PiecesModel(int pieceSize, QObject *parent) : QAbstractListModel(parent), m_PieceSize(pieceSize) @@ -77,7 +78,7 @@ QVariant PiecesModel::data(const QModelIndex &index, int role) const void PiecesModel::addPiece(const QPixmap &pixmap, const QPoint &location) { int row; - if (int(2.0 * qrand() / (RAND_MAX + 1.0)) == 1) + if (QRandomGenerator::global()->bounded(2) == 1) row = 0; else row = pixmaps.size(); diff --git a/examples/widgets/mainwindows/mainwindow/toolbar.cpp b/examples/widgets/mainwindows/mainwindow/toolbar.cpp index bb30b63b02..baea124ae4 100644 --- a/examples/widgets/mainwindows/mainwindow/toolbar.cpp +++ b/examples/widgets/mainwindows/mainwindow/toolbar.cpp @@ -50,6 +50,8 @@ #include "toolbar.h" +#include <QRandomGenerator> + #include <QMainWindow> #include <QMenu> #include <QPainter> @@ -257,7 +259,7 @@ void ToolBar::randomize() QList<QAction *> randomized; QList<QAction *> actions = this->actions(); while (!actions.isEmpty()) { - QAction *action = actions.takeAt(rand() % actions.size()); + QAction *action = actions.takeAt(QRandomGenerator::global()->bounded(actions.size())); randomized.append(action); } clear(); diff --git a/examples/widgets/statemachine/rogue/window.cpp b/examples/widgets/statemachine/rogue/window.cpp index 428d4c3af6..3515138382 100644 --- a/examples/widgets/statemachine/rogue/window.cpp +++ b/examples/widgets/statemachine/rogue/window.cpp @@ -248,11 +248,9 @@ void Window::movePlayer(Direction direction) void Window::setupMap() { - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); - for (int x = 0; x < WIDTH; ++x) for (int y = 0; y < HEIGHT; ++y) { - if (x == 0 || x == WIDTH - 1 || y == 0 || y == HEIGHT - 1 || qrand() % 40 == 0) + if (x == 0 || x == WIDTH - 1 || y == 0 || y == HEIGHT - 1 || QRandomGenerator::global()->bounded(40) == 0) map[x][y] = '#'; else map[x][y] = '.'; diff --git a/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.cpp b/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.cpp index 740d007d44..92620ddd8c 100644 --- a/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.cpp +++ b/examples/widgets/tools/plugandpaint/plugins/basictools/basictoolsplugin.cpp @@ -101,7 +101,7 @@ QRect BasicToolsPlugin::mouseMove(const QString &brush, QPainter &painter, thickness, thickness); } } else if (brush == tr("Random Letters")) { - QChar ch('A' + (qrand() % 26)); + QChar ch(QRandomGenerator::global()->bounded('A', 'Z' + 1)); QFont biggerFont = painter.font(); biggerFont.setBold(true); diff --git a/examples/widgets/tools/undo/mainwindow.cpp b/examples/widgets/tools/undo/mainwindow.cpp index aa570caa80..5976163f3f 100644 --- a/examples/widgets/tools/undo/mainwindow.cpp +++ b/examples/widgets/tools/undo/mainwindow.cpp @@ -52,6 +52,7 @@ #include <QUndoStack> #include <QFileDialog> #include <QMessageBox> +#include <QRandomGenerator> #include <QTextStream> #include <QToolButton> #include "document.h" @@ -321,7 +322,7 @@ void MainWindow::newDocument() static QColor randomColor() { - int r = (int) (3.0*(rand()/(RAND_MAX + 1.0))); + int r = QRandomGenerator::global()->bounded(3); switch (r) { case 0: return Qt::red; @@ -337,10 +338,10 @@ static QRect randomRect(const QSize &s) { QSize min = Shape::minSize; - int left = (int) ((0.0 + s.width() - min.width())*(rand()/(RAND_MAX + 1.0))); - int top = (int) ((0.0 + s.height() - min.height())*(rand()/(RAND_MAX + 1.0))); - int width = (int) ((0.0 + s.width() - left - min.width())*(rand()/(RAND_MAX + 1.0))) + min.width(); - int height = (int) ((0.0 + s.height() - top - min.height())*(rand()/(RAND_MAX + 1.0))) + min.height(); + int left = (int) ((0.0 + s.width() - min.width())*(QRandomGenerator::global()->bounded(1.0))); + int top = (int) ((0.0 + s.height() - min.height())*(QRandomGenerator::global()->bounded(1.0))); + int width = (int) ((0.0 + s.width() - left - min.width())*(QRandomGenerator::global()->bounded(1.0))) + min.width(); + int height = (int) ((0.0 + s.height() - top - min.height())*(QRandomGenerator::global()->bounded(1.0))) + min.height(); return QRect(left, top, width, height); } diff --git a/examples/widgets/tools/undoframework/diagramitem.cpp b/examples/widgets/tools/undoframework/diagramitem.cpp index 754baa2377..723645c9b2 100644 --- a/examples/widgets/tools/undoframework/diagramitem.cpp +++ b/examples/widgets/tools/undoframework/diagramitem.cpp @@ -65,8 +65,7 @@ DiagramItem::DiagramItem(DiagramType diagramType, QGraphicsItem *item) setPolygon(trianglePolygon); } - QColor color(static_cast<int>(qrand()) % 256, - static_cast<int>(qrand()) % 256, static_cast<int>(qrand()) % 256); + QColor color(QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256)); QBrush brush(color); setBrush(brush); setFlag(QGraphicsItem::ItemIsSelectable); diff --git a/examples/widgets/widgets/tetrix/main.cpp b/examples/widgets/widgets/tetrix/main.cpp index 886e94de7c..2698190e76 100644 --- a/examples/widgets/widgets/tetrix/main.cpp +++ b/examples/widgets/widgets/tetrix/main.cpp @@ -59,6 +59,5 @@ int main(int argc, char *argv[]) QApplication app(argc, argv); TetrixWindow window; window.show(); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); return app.exec(); } diff --git a/examples/widgets/widgets/tetrix/tetrixpiece.cpp b/examples/widgets/widgets/tetrix/tetrixpiece.cpp index 69e1733ac4..3d8fa86860 100644 --- a/examples/widgets/widgets/tetrix/tetrixpiece.cpp +++ b/examples/widgets/widgets/tetrix/tetrixpiece.cpp @@ -57,7 +57,7 @@ //! [0] void TetrixPiece::setRandomShape() { - setShape(TetrixShape(qrand() % 7 + 1)); + setShape(TetrixShape(QRandomGenerator::global()->bounded(7) + 1)); } //! [0] diff --git a/examples/widgets/widgets/tooltips/main.cpp b/examples/widgets/widgets/tooltips/main.cpp index 3c64a33a4c..8276b3dc8d 100644 --- a/examples/widgets/widgets/tooltips/main.cpp +++ b/examples/widgets/widgets/tooltips/main.cpp @@ -57,7 +57,6 @@ int main(int argc, char *argv[]) Q_INIT_RESOURCE(tooltips); QApplication app(argc, argv); - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); SortingBox sortingBox; sortingBox.show(); return app.exec(); diff --git a/examples/widgets/widgets/tooltips/sortingbox.cpp b/examples/widgets/widgets/tooltips/sortingbox.cpp index c15fdcf95b..4769a30c64 100644 --- a/examples/widgets/widgets/tooltips/sortingbox.cpp +++ b/examples/widgets/widgets/tooltips/sortingbox.cpp @@ -292,7 +292,7 @@ QPoint SortingBox::initialItemPosition(const QPainterPath &path) //! [24] QPoint SortingBox::randomItemPosition() { - return QPoint(qrand() % (width() - 120), qrand() % (height() - 120)); + return QPoint(QRandomGenerator::global()->bounded(width() - 120), QRandomGenerator::global()->bounded(height() - 120)); } //! [24] @@ -306,6 +306,6 @@ QColor SortingBox::initialItemColor() //! [26] QColor SortingBox::randomItemColor() { - return QColor::fromHsv(qrand() % 256, 255, 190); + return QColor::fromHsv(QRandomGenerator::global()->bounded(256), 255, 190); } //! [26] |