QT timer to use

In the program interface very easy to use, time to refresh or update something, then you should use the timer function, a timer function timer is triggered at a specified time, to achieve the effect of timing

Use the following describes two timers, do not talk nonsense directly on the code

Code structure:

 

 

 dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QTimerEvent>
#include <QDebug>
#include <QTimer>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = nullptr);
    ~Dialog();

    enum timerIndex // enumeration starts at 0 
    {
        timer1,
        timer2,
        timer3
    };

private:
    Ui :: Dialog * ui;

    QTimer *update_time;

    int id1,id2,id3;
    void timerEvent(QTimerEvent *event);
private slots:
    void time_update();

};

#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui ( new Ui :: Dialog)
{
    Despite -> setupUi ( this );
    id1 = startTimer ( 1000 );
    id2 = start timer ( 2000 );
    id3 = start timer ( 3000 );
    update_time = new QTimer();
    connect(update_time,SIGNAL(timeout()),this,SLOT(time_update()));
    UPDATE_TIME -> Start ( 1000 ); // 1 second Start

}
void Dialog::timerEvent(QTimerEvent *event)
{
    qDebug() << event->timerId() << endl;
    switch (event->timerId()-1)
    {
        case timer1 :
        qDebug() << "timer1" << endl;
        break;
        case timer2 :
        qDebug() << "timer2" << endl;
        break;
        case timer3 :
        qDebug() << "timer3" << endl;
        break;
    default:
        qDebug() << "no  !!"<<endl;
        break;
    }
}
void Dialog::time_update()
{
    qDebug() <<"update"<< endl;
}

Dialog :: ~ dialogue ()
{
    delete ui;
}

main.cpp

#include "dialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();

    return a.exec();
}

Two timers use have been introduced, can be selected according to their own situation, personal feeling is recommended to use that method to obtain a timer id, more convenient

 

Guess you like

Origin www.cnblogs.com/wanghuixi/p/12084128.html