Qt timer (1)

Timer is also a thing we often use. The following code demonstrates the basic usage of the timer.

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

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("CLOCK");              //设置窗口标题
    
    //设置标签显示信息
    ui->label->setText(QString("<center><h1>00</h1></center>"));       
    ui->label_2->setText(QString("<center><h1>00:</h1></center>"));
    ui->label_3->setText(QString("<center><h1>00:</h1></center>"));
    
    //启动定时器使用函数startTimer(),它的返回值唯一标识一个定时器
    id1 =  startTimer(1000*60*60);              //1时
    id2 = startTimer(1000*60);                     //1分
    id3 = startTimer(1000);                           //1秒
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    if(this->id3 == event->timerId()) //event有个函数叫timerId可以获取是哪个定时器发出的事件
    {
        static int num1= 0;
        if(60 == num1)
        {
            num1 = 0;
        }
        if(10 <= num1)                      //QString::number()能把一个int转换为Qstring类型。
        ui->label->setText(QString("<center><h1>%1</h1></center>").arg(QString::number(num1++)));
        else
        ui->label->setText(QString("<center><h1>0%1</h1></center>").arg(QString::number(num1++)));  
    }
    if(this->id2 == event->timerId())
    {
        static int num2= 0;
        if(60 == num2)
        {
            num2 = 0;
        }
        if(10 <= num2)
        ui->label_2->setText(QString("<center><h1>%1:</h1></center>").arg(QString::number(num2++)));
        else
        ui->label_2->setText(QString("<center><h1>0%1:</h1></center>").arg(QString::number(num2++)));    
    }
    if(this->id1 == event->timerId())
    {
        static int num3= 0;
        if(24 == num3)
        {
            num3 = 0;
        }
        if(10 <= num3)
        ui->label_3->setText(QString("<center><h1>%1:</h1></center>").arg(QString::number(num3++)));
        else
        ui->label_3->setText(QString("<center><h1>0%1:</h1></center>").arg(QString::number(num3++)));  
    }
}

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

The results are as follows:

Of course, such a CLOCK is definitely not accurate at all. Because QTimer is a timer, it does not obtain the system time. If you want to display the accurate time, you still need to obtain the system time. Using QTime is a relatively safe method.

 

Published 242 original articles · Like 180 · Visits 160,000+

Guess you like

Origin blog.csdn.net/zy010101/article/details/105424526