Qt学习笔记(5):随机数+定时器
来源:互联网 发布:淘淘商城java吧 编辑:程序博客网 时间:2024/05/10 23:58
上一节利用信号机制实现,这节利用事件处理。
关于qrand()
qrand()返回0 到
如果要返回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
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
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):随机数+定时器
- Qt学习笔记(5):随机数+定时器
- QT产生随机数和定时器
- QT产生随机数和定时器
- qt之定时器 和随机数
- Qt学习之路——— Qt定时器和随机数
- QT笔记 ---定时器
- qt学习--产生随机数
- Qt学习 之 定时器
- QT学习-定时器
- 我的QT学习笔记-02-QTimerEvent类定时器
- Qt学习笔记-定时器的应用及精度设置
- Qt学习笔记5
- 随机数 学习笔记
- 【JAVA学习笔记】随机数
- C++学习笔记-随机数
- 十、Qt Creator中实现定时器和产生随机数
- 十、Qt Creator中实现定时器和产生随机数
- QT学习(四)定时器
- mysql分区表学习
- NSNotificationCenter带参数的通知
- java-JDBC设计模式
- IntelliJ IDEA查看方法的返回类型
- Swift基础之实现下拉变大和OC下拉变大上拉缩小Demo
- Qt学习笔记(5):随机数+定时器
- andriod listview实现原理以及listview的优化
- 使用IAR和BSL下载程序至MSP430F2122
- 关于ListView多布局的一点看法
- 05#运营指标
- qrand
- jQuery 增加 删除 修改select option
- csu 1105 打怪升级 (DP)
- qrand()的用法