'I want to generate random number between the 0 to 1. with the interval of 1 second in qt

I want to generate the random value from 0 to 1 with interval of one second. i have write this code but i cannot understand how can i take delay of 1 second.

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRandomGenerator>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setStyleSheet("background-color: black;");
    ui->random_label->setAlignment(Qt::AlignCenter);
    ui->random_label->setStyleSheet("color: rgb(255, 255, 255);");
    
    while(true)
{
    double value = QRandomGenerator::global()->generateDouble();
    qDebug()<<QString::number(value,'f',2);
    //i need delay here of 1 second
}
}

MainWindow::~MainWindow()
{
    delete ui;
}

i need deley of 1 second after this line qDebug()<<QString::number(value,'f',2); in for loop and i also write the comment where i need delay of 1 second. please help i am new to Qt. how can i take delay of 1 second ?



Solution 1:[1]

Your while(true) will block in the constructor.

Instead, use a QTimer, set its interval to one second, and connect its timeout signal to a slot in your MainWindow class. In that slot, run the code currently in the body of your while.

That moves the "update random number" out of the constructor into the events-handling that is done by the application.

Solution 2:[2]

You can create a timer and attach with random generator using below example:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qtimer.h"
#include "QRandomGenerator"
#include "QDebug"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //Initialize timer
    QTimer *_timer = new QTimer(this);

    double value;
    //connect timer to random generator using lambda expression
    connect(_timer,&QTimer::timeout,[&](){
        value = QRandomGenerator::global()->generateDouble();
        qDebug()<<QString::number(value,'f',2);
    });

    //emit timeout after every 1 sec.
    _timer->start(1000);
}

MainWindow::~MainWindow()
{
    delete ui;
}

Note generateDouble() generates one random qreal in the canonical range [0, 1) (that is, inclusive of zero and exclusive of 1).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adriaan de Groot
Solution 2 smalik