
定時器方式一:----定時器事件
需要 #include <QTimerEvent>
#include "win.h" #include <QDebug> #include <QPushButton> Win::Win(QWidget *parent) : QWidget(parent) { this->resize(500,400); this->setWindowTitle("定時器"); this->move(700,100); QPushButton* btn=new QPushButton("按鈕",this); btn->move(400,350); connect(btn,&QPushButton::clicked,this,&Win::A); label=new QLabel("標簽標簽",this); label->move(10,10); label->resize(200,50); label->setFrameShape(QFrame::Box); label1=new QLabel("標簽1",this); label1->move(10,70); ID=startTimer(1000);//啟動定時器事件,創建一個定時器並返回定時器ID //參數:單位毫秒---每隔n毫秒時間,就執行一次定時器事件 //返回值:定時器ID號 ID1=startTimer(2000); } void Win::timerEvent(QTimerEvent *e){ static int i,j=0; if(e->timerId()==ID){ //如果定時號是ID label->setText(QString::number(i++)); } if(e->timerId()==ID1){ label1->setText(QString::number(j++)); } } Win::~Win() { } void Win::A(){ }
定時器方式二:----QTimer類--推薦
需要 #include <QTimer>
#include "win.h" #include <QDebug> #include <QPushButton> Win::Win(QWidget *parent) : QWidget(parent) { this->resize(500,400); this->setWindowTitle("定時器"); this->move(700,100); QPushButton* btn=new QPushButton("按鈕",this); btn->move(400,350); connect(btn,&QPushButton::clicked,this,&Win::A); label=new QLabel("標簽標簽",this); label->move(10,10); label->resize(200,50); label->setFrameShape(QFrame::Box); label1=new QLabel("標簽1",this); label1->move(10,70); timer1=new QTimer(this); //創建定時器對象 timer1->start(500); //啟動定時器 //參數:每個n毫秒發送信號(timeout),單位:毫秒 connect(timer1,&QTimer::timeout,[=](){ static int i=0; label->setText(QString::number(i++)); }); //信號連接函數 //QTimer::timeout 時間到信號 //timer1->stop();//定時器停止 } Win::~Win() { } void Win::A(){ }

