https://www.cnblogs.com/doker/p/11150053.html
工程目录:
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();
</span><span style="color: #0000ff;">void</span><span style="color: #000000;"> on_buttonStop_clicked();
private:
Ui::Widget *ui;
QTimer </span>*myTimer;<span style="color: #008000;">//</span><span style="color: #008000;"> 定时器对象</span>
};
#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 </span>= <span style="color: #0000ff;">new</span> QTimer(<span style="color: #0000ff;">this</span><span style="color: #000000;">);
connect(myTimer,</span>&QTimer::timeout,[=<span style="color: #000000;">](){
</span><span style="color: #0000ff;">static</span> <span style="color: #0000ff;">int</span> i = <span style="color: #800080;">0</span><span style="color: #000000;">;
i</span>++<span style="color: #000000;">;
ui</span>->lcdNumber-><span style="color: #000000;">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()
{
</span><span style="color: #0000ff;">if</span>(myTimer->isActive() == <span style="color: #0000ff;">true</span><span style="color: #000000;">)
{
myTimer</span>-><span style="color: #000000;">stop();
}
}
UI: