目录
一、继承QObject定时器事件
所有继承自QObject的类,都会有一个timerEvent(QTimerEvent *event)的纯虚函数,startTimer()设定定时间隔并启动,再重载这个函数以处理自己的定时任务,多个定时任务用timeId区分,结束后使用killTimer(timerid)关闭定时任务。
void timerEvent(QTimerEvent *event); //重写定时器事件(继承QObject)
int timerId; //定时器ID(继承QObject)
timerId=startTimer(1000); //启动定时器并获取定时器ID(继承QObject)
void QtWidgetsApplication19::timerEvent(QTimerEvent* event) //重写定时器事件
{
if (event->timerId()== timerId) //判断定时器ID,确定是哪个定时器
{
//需要运行的内容
}
}
二、QTimer类
使用信号与槽connect的形式完成定时任务,创建一个QTimer类对象,调用start函数完成定时和启动。
QTimer *timer=new QTimer(); //定时器(QTimer类)
void starttimer(); //定时器槽函数(QTimer类)
connect(timer,&QTimer::timeout,this,&QtWidgetsApplication19::starttimer);
三、具体实现
ui界面如下:
QtWidgetsApplication19.h
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QtWidgetsApplication19.h"
#include <QTimer>
#include <QDateTime>
#include <QDebug>
#include <QObject>
class QtWidgetsApplication19 : public QMainWindow
{
Q_OBJECT
public:
QtWidgetsApplication19(QWidget *parent = nullptr);
~QtWidgetsApplication19();
QTimer *timer=new QTimer(); //定时器(QTimer类)
void starttimer(); //定时器槽函数(QTimer类)
void timerEvent(QTimerEvent *event); //重写定时器事件(继承QObject)
int timerId; //定时器ID(继承QObject)
private:
Ui::QtWidgetsApplication19Class ui;
};
QtWidgetsApplication19.cpp
#include "QtWidgetsApplication19.h"
QtWidgetsApplication19::QtWidgetsApplication19(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
connect(timer,&QTimer::timeout,this,&QtWidgetsApplication19::starttimer);
connect(ui.pushButton, &QPushButton::clicked, [=]() {
timer->start(1000); //启动定时器,间隔1s(QTimer类)
});
connect(ui.pushButton_2, &QPushButton::clicked, this, [=]() {
timerId=startTimer(1000); //启动定时器并获取定时器ID,间隔1s(继承QObject)
});
}
void QtWidgetsApplication19::starttimer()
{
QDateTime dt = QDateTime::currentDateTime(); //获取系统时间
ui.textEdit->append(dt.toString("dd.MM.yyyy hh:mm:ss")); //打印系统时间
}
void QtWidgetsApplication19::timerEvent(QTimerEvent* event) //重写定时器事件
{
if (event->timerId()== timerId) //判断定时器ID,确定是哪个定时器
{
QDateTime dt = QDateTime::currentDateTime();
ui.textEdit_2->append(dt.toString("dd.MM.yyyy hh:mm:ss"));
}
}
QtWidgetsApplication19::~QtWidgetsApplication19()
{
}
main.cpp
#include "QtWidgetsApplication19.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QtWidgetsApplication19 w;
w.show();
return a.exec();
}
实现效果: