widget.h
#ifndef WIDGET_H#define WIDGET_H#include <QWidget>#include <QTimer>namespace Ui {class Widget;}class Widget : public QWidget{ Q_OBJECTpublic: explicit Widget(QWidget *parent = 0); ~Widget();PRivate slots: void on_buttonStart_clicked(); void on_buttonStop_clicked(); void on_buttonClear_clicked();private: Ui::Widget *ui; QTimer *myTimer;};#endif // WIDGET_Hwidget.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); this->setWindowTitle("我的定时器"); connect(myTimer, &QTimer::timeout, [=]() { static int i = 0; i++; ui->lcdNumber->display(i); } );}Widget::~Widget(){ delete ui;}void Widget::on_buttonStart_clicked(){ //启动定时器,时间间隔为100毫秒,每个100毫秒定时器自动触发myTimer的timeout信号 myTimer->start(100);}void Widget::on_buttonStop_clicked(){ myTimer->stop();}void Widget::on_buttonClear_clicked(){ ui->lcdNumber->display(0);}main.cpp#include "widget.h"#include <Qapplication>int main(int argc, char *argv[]){ QApplication a(argc, argv); Widget w; w.show(); return a.exec();}
新闻热点
疑难解答