工程目录:
widget.h:
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QTimer> // 定时器对象 namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private slots: void on_buttonStart_clicked(); void on_buttonStop_clicked(); private: Ui::Widget *ui; QTimer *myTimer;// 定时器对象 }; #endif // WIDGET_H
widget.cpp:
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); myTimer = new QTimer(this); connect(myTimer,&QTimer::timeout,[=](){ static int i = 0; i++; ui->lcdNumber->display(i); }); } Widget::~Widget() { delete ui; } //按钮Start,转到槽 void Widget::on_buttonStart_clicked() { //启动定时器 //时间间隔为100ms //每隔100ms,定时器myTimer自动触发timeout() //如果定时器没有激活,才启动,防止多次点击start按钮出现错误 if (myTimer->isActive() == false) { myTimer->start(100); } } void Widget::on_buttonStop_clicked() { if(myTimer->isActive() == true) { myTimer->stop(); } }
UI: