Qt学习笔记(5):随机数+定时器

上一节利用信号机制实现,这节利用事件处理。

关于qrand()

qrand()返回0 到 RAND_MAX间的值。</wbr>

如果要返回0~n间的值,则为:qrand()%n。

如果要返回a~b间的值,则为:a + qrand() % (b – a)。

关于secsTo()

int QTime::secsTo ( const QTime & t ) const

返回这个时间到t的秒数(如果t早于这个时间,返回的为负数)。

因为QTime只能度量一天之内的时间,而且一天内只有86400秒,所以结果就应该在-86400秒和86400秒之间。

关于qsrand()

官方解释:

Thread-safe version of the standard C++ srand() function.

Sets the argument seed to be used to generate a new random number sequence of pseudo random integers to be returned by qrand().

The sequence of random numbers generated is deterministic per thread.
For example, if two threads call qsrand(1) and subsequently calls qrand(), the threads will get the same random number sequence.

大致意思就是用qsrand()产生一个可以被qrand()返回的数值。(我是这么理解的,有错误请高手斧正!)而且每个线程调用qsrand(1)(这里1可以随便取,比如2,3,4..n)之后,随后用qrand()返回的值相同。

所以如果程序没有qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));这句的话,那么每次运行都会产生相同的随机数,那也就不叫随机数了。

MainWindow.h

01  #ifndef MAINWINDOW_H
02  #define MAINWINDOW_H
03
04  #include </span>
05
06 namespace Ui {
07     class MainWindow;
08 }
09
10 class MainWindow : public QMainWindow
11 {
12     Q_OBJECT
13
14 public:
15     explicit MainWindow(QWidget *parent = );
16     ~MainWindow();
17     void timerEvent(QTimerEvent *);
18 private:
19     Ui::MainWindow *ui;
20     int id1,id2,id3;
21 };
22
23 #endif // MAINWINDOW_H </div> MainWindow.cpp
01  #include “mainwindow.h”
02  #include “ui_mainwindow.h”
03  #include </span>
04 MainWindow::MainWindow(QWidget *parent:
05     QMainWindow(parent),
06     ui(new Ui::MainWindow)
07 {
08     ui->setupUi(this);
09     id1=startTimer(1000);//其返回值为1,timerID为1
10     id2=startTimer(10000);//其返回值为2,timerID为2
11     id3=startTimer(20000);//其返回值为3,timerID为3
12     qsrand(QTime(,,).secsTo(QTime::currentTime()));
13 }
14
15 MainWindow::~MainWindow()
16 {
17     delete ui;
18 }
19 void MainWindow::timerEvent(QTimerEvent *t)//定时器事件
20 {
21     if (t->timerId()==id1)
22     {
23         ui->label->setText(tr(“每秒产生一个随机数: %1 , 10秒后启动label2~~”).arg(qrand()%10));
24     }
25     else if (t->timerId()==id2)
26     {
27          ui->label_2->setText(tr(“HI~~我是label2,10秒后程序将关闭”));
28     }
29     else
30     {
31         qApp->quit();
32     }
33 }</div>

下载源码

转载请注明:于哲的博客 » Qt学习笔记(5):随机数+定时器

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值