定时器类相比于定时器事件使用的更多
展示:
代码:
//widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
//定时器事件
void timerEvent(QTimerEvent *);
//第一个定时器id
int m_Id1;
//第二个定时器id
int m_Id2;
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
//widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "QTimerEvent"
#include "QTimer"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//启动定时器
this->m_Id1 = startTimer(1000); //ms
this->m_Id2 = startTimer(2000);
//定时器类
QTimer *timer = new QTimer(this);
timer->start(500);//ms
//监听定时器对象的信号
connect(timer,&QTimer::timeout,[=](){
static int num3 =1;
ui->label_3->setText(QString::number(num3++));
});
//点击暂停,实现停止定时器
connect(ui->btn_stop,&QPushButton::clicked,[=](){
timer->stop();
});
}
//定时器事件
void Widget::timerEvent(QTimerEvent *e){
if(e->timerId() == this->m_Id1){
static int num=1;
ui->label->setText(QString::number(num++));
}
if(e->timerId() == this->m_Id2){
static int num2=1;
ui->label_2->setText(QString::number(num2++));
}
}
Widget::~Widget()
{
delete ui;
}