Qt两种定时器案例

本文通过实例代码介绍了Qt中两种不同的定时器用法,详细讲解了头文件和源文件的实现,并展示了具体运行效果。

一、头文件中的代码

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include <QMessageBox>
#include <QObject>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
     void timerEvent(QTimerEvent *ev);

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
    int m_id1, m_id2;
    QTimer m_timer;
    QString m_err_info;
};

#endif // MAINWINDOW_H

二.源文件中的代码

#include "mainwindow.h"
#include "ui_mainwindow.h"

#define MESSAGE_RED "<font size = 200 color = red ><strong>"
#define MESSAGE_GREEN "<font size = 200 color = blue ><strong>"
#define MESSAGE_END "</strong></font>"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    m_id1 = startTimer(800); // 1000ms
    m_id2 = startTimer(500); // 1000ms
    static int c = 15;
    m_timer.start(1000);
    connect(&m_timer, &QTimer::timeout, this, [=]()
    {
        c--;
        if(c == 0)
        {
           c=15;
           m_err_info = tr("初始化环境成功");
           QString str1 = MESSAGE_RED + m_err_info + MESSAGE_END;
           QMessageBox::information(this,tr("信息"), str1);
           m_timer.stop();
        }
        m_err_info = tr("请在") + QString::number(c)+tr("秒后弹出初始化环境成功后点击开始测试...");
        ui->label_2->setText(m_err_info);
    });
}

void MainWindow::timerEvent(QTimerEvent *ev)
{
    if(ev->timerId() == m_id1)
    {
        static int a = 15;
        a--;
        if(a == 0)
        {
           a=15;
           m_err_info = tr("初始化环境成功");
           QString str1 = MESSAGE_RED + m_err_info + MESSAGE_END;
           QMessageBox::information(this,tr("信息"), str1);
           killTimer(m_id1);
        }
        m_err_info = tr("请在") + QString::number(a)+tr("秒后弹出初始化环境成功后点击开始测试...");
        ui->label_4->setText(m_err_info);
    }
    if(ev->timerId() == m_id2)
    {
        static int b = 15;
        b--;
        if(b == 0)
        {
           b=15;
           m_err_info = tr("初始化环境成功");
           QString str1 = MESSAGE_RED + m_err_info + MESSAGE_END;
           QMessageBox::information(this,tr("信息"), str1);
            killTimer(m_id2);
        }
        m_err_info = tr("请在") + QString::number(b)+tr("秒后弹出初始化环境成功后点击开始测试...");
        ui->label_6->setText(m_err_info);
    }
}

三.效果展示

这里写图片描述

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

The_Web3_社区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值