Qt +QTimer 定时器的使用

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>&amp;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>-&gt;lcdNumber-&gt;<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-&gt;isActive() == <span style="color: #0000ff;">true</span><span style="color: #000000;">)
{
    myTimer</span>-&gt;<span style="color: #000000;">stop();
}

}

复制代码

UI:

发布了42 篇原创文章 · 获赞 148 · 访问量 41万+

猜你喜欢

转载自blog.csdn.net/baidu_37503452/article/details/104219170