Generating random-value integers in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

Overview[edit | edit source]

This code snippet shows how to generate a random integer in Qt.

Preconditions[edit | edit source]

Source[edit | edit source]

  1. include <QGlobal.h>
  2. include <QTime>

int QMyClass::randInt(int low, int high)

   {
   // Random number between low and high
   return qrand() % ((high + 1) - low) + low;
   }

// Create seed for the random // That is needed only once on application startup QTime time = QTime::currentTime(); qsrand((uint)time.msec());

// Get random value between 0-100 int randomValue = randInt(0,100);


Postconditions[edit | edit source]

A random number is given.