QTimer
执行多次
//.h文件--声明QTimer对象和槽函数
public :
void timerFun();
private:
QTimer* demoTimer;
//.cpp文件--实例化和连接信号槽
demoTimer= new QTimer();
connect(demoTimer, &QTimer::timeout, this, &MyWidget::timerFun)); //信号和槽
demoTimer->setInterval(10000); //10s
demoTimer->start();
//定时时间到后,调用该槽函数
void MyWidget::timerFun()
{
qDebug()<<"timer out";
}
只执行一次Timeout
- 当调用只执行一遍的操作时,可以使用QTimer的简约用法,singleShot()函数。
//.cpp文件--使用singleShot静态函数,此时不需要实例化QTimer
QTimer::singleShot(10000, this, SLOT(onZipTodayFile()));
不能同时使用两个QTimer
在某个Widget 界面上,定义两个QTimer, 不同的定时器干不同的工作
QTimer *timer1 = new QTimer(this);
QTimer *timer2 = new QTimer(this);
timer1->start(100);
timer2->start(1000);
connect(timer1, &QTimer::timeout, this, Timer1_Fuc);
connect(timer2, &QTimer::timeout, this, Timer2_Fuc);
但是运行的时候发现,timer2连接的槽函数Timer2_Fuc()一直没有触发。
难道是一个线程内不能有两个定时器同时工作?
timerEvent的用法
//.h中, 定义两个timer的identifier
protected:
//定时器事件,可以同时触发过个定时器工作
void timerEvent(QTimerEvent *);
private:
int timer1;
int timer2;
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
timer1 = 0;
timer2 = 0;
timer1 = startTimer(100); //Starts a timer and returns a time identifier
timer2 = startTimer(200); //Starts a timer and returns a time identifier
}
//重写timerEvent函数
void Widget::timerEvent(QTimerEvent *e)
{
if(e->timerId() == timer1)
{
static int i = 0;
i++;
qDebug()<<"i = "<<i;
if(i == 100)
{
killTimer(timer1);
timer1 = 0;
}
}
else if(e->timerId() == timer2)
{
static int j = 0;
j++;
qDebug()<<"j = "<<j;
if(j == 200)
{
killTimer(timer2);
timer2 = 0;
}
}
}