QTimer class for Qt learning

QTimer class

1. Introduction

The QTimer class provides repeating and one-shot timers.

2. How to use

  1. create timer
QTimer *time=new QTimer();
  1. Create a signal and slot
    Timeout () signal will be sent after the time expires, so after creating the timer object, create a signal and slot for it, and complete the operation of the corresponding slot by responding to the timeout () signal.
connect(time,SIGNAL(timeout()),this,SLOT(onTimeout());
  1. Turn on the timer and set the timing period.
    The msec parameter indicates the timing period in milliseconds. If you want to operate for one second, you need to set the value of msec to 1000.
time->start(int msec);

3. Example (display the current time on the label text box)
Add the slot function you set in the .h file

public slots:
    void HandleTime();
private:
    Ui::QtQListClass ui;
    QTimer *time;

Add in .cpp

#define AVERAGE_TIME 1000 //设置定时器周期为1秒
time = new QTimer();
connect(time, SIGNAL(timeout()), this, SLOT(HandleTime()));
time->start(AVERAGE_TIME);

void QtQList::HandleTimeout() {
    
    
   QTime qTime= QTime::currentTime();//获取当前系统的时间
   ui.label->setText(qTime.toString("hh:mm:ss"));//设置时间显示格式
}

display effect:

renderings

Guess you like

Origin blog.csdn.net/m0_56626019/article/details/129818982