QTimer类使用方法。

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 

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();

    void on_buttonClear_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);

    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 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}



你可能感兴趣的:(QT学习之路)