第一种定时器qtimer
头文件qtimer.h
构造函数
QTimer::QTimer(QObject *parent = Q_NULLPTR)
常用函数
void
setInterval(int msec)//设置间隔时长
int
interval() const//返回间隔时长单位ms
int
remainingTime() const//返回剩余时长
void
setSingleShot(bool singleShot)//设置单一模式
void
setTimerType(Qt::TimerType atype)//设置定时器精度类型
Qt::PreciseTimer
0
Precise timers try to keep millisecond accuracy //毫秒误差
Qt::CoarseTimer
1
Coarse timers try to keep accuracy within 5% of the desired interval//百分之5以内误差 默认属性
Qt::VeryCoarseTimer
2
Very coarse timers only keep full second accuracy//秒误差
使用案例
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->setFixedSize(800,600);
QTimer* timer=new QTimer(this);
timer->setInterval(2000);
timer->setSingleShot(true);
timer->setTimerType(Qt::VeryCoarseTimer);
connect(timer,SIGNAL(timeout()),this,SLOT(myslots()));
timer->start();
}
Widget::~Widget()
{
delete ui;
}
void Widget::myslots()
{
qDebug()<<"触发槽函数";
}
第二种继承来的定时器
需要重写虚函数void QObject::timerEvent ( QTimerEvent * event )
常用函数:
int QObject::startTimer(int interval, Qt::TimerType timerType = Qt::CoarseTimer)//启动定时器并返回id用于杀死定时器,单位毫秒
void QObject::killTimer(int id) //杀死定时器
示例:
int id;
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->setFixedSize(800,600);
id=startTimer(1000,Qt::VeryCoarseTimer);
}
void Widget::timerEvent(QTimerEvent *event)
{
killTimer(event->timerId());
qDebug()<<"杀死定时器"<<event->timerId();
}