Qt event system: timers and timed events

1. Timer

Declare in the header file .h:

private slots:
    void timeOut(); // 定时器超时槽函数

Implement the corresponding function in .cpp:

// 构造函数
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 创建一个新的定时器
    QTimer *timer = new QTimer(this);
    // 设置定时器1秒钟超时
	timer->setInterval(100);        
    // 关联定时器的超时信号到槽上
    connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
	// 开始计时
    timer->start();      
}

// 定时器超时槽函数
void Widget::timeOut()
{
    QTime time = QTime::currentTime();      // 获取当前时间
    QString text = time.toString("hh:mm:ss");  // 转换为字符串
    if((time.second() % 2) == 0)
    {
        // 每隔一秒就将“:”显示为空格
        text[2]=' ';
        text[5]=' ';
    }
    qDebug() << text;
}

Here, a 1-second timer is opened in the constructor, and when it overflows, the timeout() signal will be emitted, and our timer overflow processing function will be executed at this time. In the slot we get the current time and convert it to a displayable string.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

The Application Output window outputs the following:

"15:36:23"
"15 36 24"
"15:36:25"
"15 36 26"

If we want this timer to count only once, we must use the void setSingleShot(bool singleShot) function.

QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
timer->setsetSingleShot(true)
timer->start(60000);

This way the timer will only count down for 1 minute and then end.

2. Timing events

The QTimerEvent class is used to describe a timer event. For a subclass of QObject, you only need to use the int QObject::startTimer (int interval) function to start a timer. This function needs to input an integer in milliseconds as a parameter to indicate the set time, and it returns a Integer number to represent this timer. When the timer overflows, you can get the number of the timer in the timerEvent() function to perform related operations.

Use the timerId() function of QTimerEvent to get the number of the timer, and then determine which timer it is and perform different operations respectively.

Declare in the header file .h:

private:
    Ui::Widget *ui;

    int id1,id2,id3; // 定时器的编号

protected:
    void timerEvent(QTimerEvent *event); // 定时器事件

Implement the corresponding function in .cpp:

// 构造函数
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    id1 = startTimer(1000); // 开启一个1秒定时器,并返回其id
    id2 = startTimer(2000);
    id3 = startTimer(4000);
}

// 定时器事件
void Widget::timerEvent(QTimerEvent *event)
{
    // 1秒钟时间到,则定时器1溢出
    if (event->timerId() == id1)
    {
        qDebug()<<"timer1";
    }
    else if(event->timerId() == id2)
    {
        qDebug()<<"timer2";
    }
    else if (event->timerId() == id3)
    {
        qDebug()<<"timer3";
    }
}

The Application Output window outputs the following:

timer1
timer1
timer2
timer1
timer1
timer2
timer3

3. Extension: random number

Declare in the header file .h:

private slots:
    void timeOut(); // 定时器超时函数

Implement the corresponding function in .cpp:

// 构造函数
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 创建一个新的定时器
    QTimer *timer = new QTimer(this);
    // 设置定时器1秒钟超时
    timer->start(1000);
    // 关联定时器的超时信号到槽上
    connect(timer,SIGNAL(timeout()),this,SLOT(timeOut()));

    // 使用qsrand()函数为随机数设置初值
    qsrand(static_cast<uint>( QTime(0, 0, 0).secsTo(QTime::currentTime()) ));
}

// 定时器超时函数
void Widget::timeOut()
{
    int rand = qrand()%300; // 产生300以内的正整数
    qDebug()<< rand;
}

Before using the qrand() function to generate random numbers, generally use the qsrand() function to set the initial value for it. If the initial value is not set, then each time the program is run, qrand() will generate the same set of random numbers.

In order to generate different random numbers each time the program is run, we need to use qsrand() to set a different initial value. The secsTo() function of the QTime class is used here, which indicates the number of seconds between two time points, for example, the code refers to the number of seconds elapsed from zero o'clock to the current time.

When using qrand() to obtain a value within a range, it is generally used to take the remainder with an integer, for example, here the remainder with 300 will make all generated values ​​between 0-299.

The Application Output window outputs the following:

112
212
223
102

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/QtCompany/article/details/131773537