QT 定時器的使用方法


在界面程序中很容易使用到,定時刷新或者更新什么東西,此時應該使用定時器的功能,定時器是在指定時間觸發定時器函數,來達到定時的效果

接下來介紹兩種定時器的使用,廢話不說直接上代碼

代碼結構:

 

 

 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 //枚舉從 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)
{
    ui->setupUi(this);
    id1 = startTimer(1000);
    id2 = startTimer(2000);
    id3 = startTimer(3000);
    update_time = new QTimer();
    connect(update_time,SIGNAL(timeout()),this,SLOT(time_update()));
    update_time->start(1000); //1秒鍾后啟動

}
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::~Dialog()
{
    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();
}

兩種定時器使用方法已經介紹,可以根據自己的實際情況進行選擇使用,個人感覺推薦使用獲取定時器id 的那種方法,比較方便

 工程代碼在此鏈接需要自行下載

鏈接:https://pan.baidu.com/s/1iM3IgRzfEoOD21ek1L_GVQ 
提取碼:hcqy

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM