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 ?
-
Use a QTimer to execute a slot every second.
-
@Christian-Ehrlicher but my requirement is to generate in infinite loop ad show in window.
-
@JonB said in I want to generate random number between the 0 to 1. with the interval of 1 second in qt.:
Trust us :)
Trust-Rule #1: Never trust someone on the internet who said "Trust me" XD
... unless it's an African prince who want to send you money or you've won the lottery :o)
[Edit: No, kids... dont do that :) ] -
@dev_liya said in I want to generate random number between the 0 to 1. with the interval of 1 second in qt.:
but my requirement is to generate in infinite loop ad show in window.
If you do an infinite loop then the event loop will not run. That means that setting the
random_label
or anything like that will not show on the screen as the slots cannot be handled: your infinite loop will block the event loop. The effect is that you have a frozen application. So, trust @JonB.As per your request: to wait for one second and block everything (you have been warned!): use
QThread::sleep(1);