定时器事件QtimerEvent 随机数 qrand Qtimer定时器

QTimerEvent类:定时器事件。QObject的子类都可使用  int QObject::startTimer(int interval)【参数:毫秒】【返回值:定时器整型编号】来开启一个定时器。定时器溢出是,触发timerEvent()函数。

QTimer类:定时器。编程中更常用。提供更高层次的编程接口,可使用信号和槽,可设定只运行一次。帮助:Timers

一:定时器事件类QTimerEvent

//widget.h
/...
#include <QTimerEvent>
enum timerIndex
{
    timer1,
    timer2,
    timer3
};

//...
private:
    void timerEvent(QTimerEvent *event);
private:
    int id1,id2,id3; //定时器对象的ID
//widget.cpp

#include <QDebug>
//...
    id1 = startTimer(1000);//1s定时器
    id2 = startTimer(3000);//3s定时器
    id3 = startTimer(5000);//5s定时器

//...
void Widget::timerEvent(QTimerEvent *event)//这里面可以分别调用针对每个定时器的事件处理函数
{
    switch(event->timerId()-1)  //timerId()获取定时器的编号
    {
        case timer1:
            qDebug()<<tr("1s定时器触发")  ;
            break;
        case timer2:
            qDebug()<<tr("3s定时器触发");
            break;
         case timer3:
            qDebug()<<tr("5s定时器触发");
            break;
    default:
        return;
    }
}

 二:定时器QTimer类(实现电子表)

//widget.h

#include <QTimer>
#include <QTime>
//...

private slots:
    void timerUpdate();
//widget.cpp

//...
    QTimer * timer = new QTimer(this); //创建一个新的定时器
    connect(timer,&QTimer::timeout,this,&Widget::timerUpdate);//关联定时器的溢出信号到槽上
    timer->start(1000); //启动并设置溢出时间1s

//...
void Widget::timerUpdate()
{
    QTime time = QTime::currentTime(); //获取当前时间
    QString text = time.toString("hh:mm");
    if((time.second()%2) == 0)
        text[2] = ' ';
    ui->lcdNumber->display(text);
}

QTimer类还有个 singleSlot()函数来开启一个只运行一次的定时器,时间溢出则触发事件

 QTimer::singleShot(5000,this,&Widget::close);//5s后窗口自动关闭

三、随机数qrand  qsrand

 使用qrand()之前,一般先用qsrand()设置初值。如果不设置初值,那么程序每次运行qrand()将产生相同的一组随机数。

    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));//得到 两个时间之间包含的秒速
    int randNum = qrand()%300;//产生300以内的随机数
    QString text = QString::number(randNum,10); 
    ui->lcdNumber->display(text);

原文地址:https://www.cnblogs.com/azbane/p/8670742.html