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 的那种方法,比较方便

猜你喜欢

转载自www.cnblogs.com/wanghuixi/p/12084128.html