I want to generate random number between the 0 to 1. with the interval of 1 second in qt.
-
wrote on 27 Jan 2022, 11:41 last edited by
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.
-
Use a QTimer to execute a slot every second.
wrote on 27 Jan 2022, 12:00 last edited by@Christian-Ehrlicher but my requirement is to generate in infinite loop ad show in window.
-
@Christian-Ehrlicher but my requirement is to generate in infinite loop ad show in window.
wrote on 27 Jan 2022, 12:01 last edited by JonB@dev_liya
You do not need any loop.QTimer
can be set to fire every second for you, repeatedly. Put a slot on that to pick a random number and display it. No "loop" nor "delay" required. Get rid of anywhile(true)
. Trust us :) -
@dev_liya
You do not need any loop.QTimer
can be set to fire every second for you, repeatedly. Put a slot on that to pick a random number and display it. No "loop" nor "delay" required. Get rid of anywhile(true)
. Trust us :)wrote on 27 Jan 2022, 13:21 last edited by Pl45m4@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 :) ] -
@Christian-Ehrlicher but my requirement is to generate in infinite loop ad show in window.
wrote on 28 Jan 2022, 07:40 last edited by@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);
6/6