方法一
1、重写虚函数
void timerEvent(QTimerEvent* e);
2、启动定时器
int startTimer(int interval)
代码
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTimerEvent>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
protected:
void timerEvent(QTimerEvent *e);
private slots:
void on_pushButton_clicked();
void on_pushButton_close_clicked();
private:
Ui::Widget *ui;
int timerId;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
// 定时间隔到,系统会自动调用该函数
void Widget::timerEvent(QTimerEvent *e)
{
//进行相关业务
if(e->timerId() == timerId){
static int i = 0;
ui->lineEdit->setText(QString("timer: %1").arg(i++));
}
}
void Widget::on_pushButton_clicked()
{
// 启动定时器。参数:定时时间(ms)
timerId = startTimer(1000);
}
void Widget::on_pushButton_close_clicked()
{
killTimer(timerId);
}
方法2
1、定义一个QTimer对象
QTimer* timer;
2、启动定时器
void QTimer::start(std::chrono::milliseconds msec)
3、连接信号槽
- 定时间隔到,QTimer对象会发出一个timeout信号。连接信号槽,在槽函数中进行相关操作
[signal] void QTimer::timeout()
代码
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTimer>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_pushButton_clicked();
void on_pushButton_close_clicked();
void timeoutSlot();
private:
Ui::Widget *ui;
QTimer* timer;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
timer = new QTimer(this);
//连接信号槽
connect(timer, &QTimer::timeout, this, &Widget::timeoutSlot);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
//启动定时器
timer->start(1000);
}
void Widget::on_pushButton_close_clicked()
{
//关闭定时器
timer->stop();
}
void Widget::timeoutSlot()
{
//进行相关业务
static int i = 0;
ui->lineEdit->setText(QString("timer: %1").arg(i++);
}
效果