您的位置:首页 > 编程语言 > Qt开发

Qt QTimer 笔记(持续更新中)

2018-01-19 21:59 281 查看
1.QTimer有设置定时器功能,下面是start函数重载的用法

[slot]void QTimer::start(intmsec)

//在状态栏实时显示系统时间

QStatusBar *sBar=statusBar();
QLabel *timeLabel=new QLabel(this);
sBar->addWidget(timeLabel);
QTimer *timer=new QTimer(this);
timer->start(1000);
connect(timer,&QTimer::timeout,
   [=]()mutable
   {
   QDateTime time=QDateTime::currentDateTime();
   QString str=time.toString("yyyy-MM-dd dddd hh:mm:ss ");
   timeLabel->setText(str);
   }
  );

[slot]void QTimer::start()

//点击菜单的开始,每隔50ms生成八位随机数
timer1=new QTimer(this);
timer1->setInterval(50);
qsrand((unsigned)time(NULL));
 connect(ui->actionStart,&QAction::triggered,timer1,static_cast<void(QTimer::*)()>(&QTimer::start));      connect(ui->actionStart,&QAction::triggered,
[=]()mutable
{
stopflag=true;
}
);
connect(timer1,&QTimer::timeout,
[=]()mutable
{
int a=rand();                ui->lcdNumber->display(a);
}
);

此处的timer1是成员变量,当timer1要停的时候,用timer1->stop();

还可以用startTimer()和killTimer()以及重写timerEvent函数来实现定时器

TimerId=startTimer(1000);

void MainWindow::timerEvent(QTimerEvent *event)
{
static int sec=0;
sec++;
if(sec==2)
{
killTimer(TimerId);
answerlabel->setText("");
sec=0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  QT